Remove characters from NSString?
NSString *myString = @"A B C D E F G";
I want to remove the spaces, so the new string would be "ABCDEFG".
Solution 1:
You could use:
NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:@" " withString:@""];
Solution 2:
If you want to support more than one space at a time, or support any whitespace, you can do this:
NSString* noSpaces =
[[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:@""];
Solution 3:
Taken from NSString
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
Parameters
target
The string to replace.
replacement
The string with which to replace target.
Return Value
A new string in which all occurrences of target in the receiver are replaced by replacement.