How to remove whitespace in a string?

后端 未结 13 2136
天涯浪人
天涯浪人 2020-12-17 08:12

I have a string say \"Allentown, pa\"

How to remove the white space in between , and pa using objective c?

相关标签:
13条回答
  • 2020-12-17 08:42

    Here is a proper and documented way of removing white spaces from your string.

    whitespaceCharacterSet Apple Documentation for iOS says:

    Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
    
    + (id)whitespaceCharacterSet
    Return Value
    A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
    
    Discussion
    This set doesn’t contain the newline or carriage return characters.
    
    Availability
    Available in iOS 2.0 and later.
    

    You can use this documented way:

    [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    

    Hope this helps you.

    If you need any more help then please let me know on this.

    0 讨论(0)
  • 2020-12-17 08:44

    If you want to white-space and new-line character as well then use "whitespaceAndNewlineCharacterSet" instead of "whitespaceCharacterSet"

     NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
     NSString *trimmedString = [temp.text stringByTrimmingCharactersInSet:whitespace];
    
     NSLog(@"Value of the text field is %@",trimmedString);   
    
    0 讨论(0)
  • 2020-12-17 08:44
    NSString *sample = @" string with whitespaces";
    NSString *escapeWhiteSpaces = [sample stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    0 讨论(0)
  • 2020-12-17 08:44

    Here is the proper way to remove extra whitespaces from string which is coming in between.

    NSString *yourString = @"Allentown,   pa";
    NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
    NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
    
    NSArray *parts = [yourString componentsSeparatedByCharactersInSet:whitespaces];
    NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
    yourString = [filteredArray componentsJoinedByString:@" "];
    
    0 讨论(0)
  • 2020-12-17 08:44

    Hi there is the swift version of the solution with extension :

    extension String{
        func deleteSpaces() -> String{
            return self.stringByReplacingOccurrencesOfString(" ", withString: "")
        }
    }
    

    And Just call

    (yourString as! String).deleteSpaces()
    
    0 讨论(0)
  • 2020-12-17 08:45
    - (NSString *)removeWhitespaces {
      return [[self componentsSeparatedByCharactersInSet:
                        [NSCharacterSet whitespaceCharacterSet]]
          componentsJoinedByString:@""];
    }
    
    0 讨论(0)
提交回复
热议问题