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".

144664 次浏览

You could use:

NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:@" " withString:@""];

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:@""];

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.

if the string is mutable, then you can transform it in place using this form:

[string replaceOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, string.length)];

this is also useful if you would like the result to be a mutable instance of an input string:

NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, string.length)];

You can try this

- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
while ([str rangeOfString:@"  "].location != NSNotFound) {
str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
}
return str;
}

Hope this will help you out.

All above will works fine. But the right method is this:

yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

It will work like a TRIM method. It will remove all front and back spaces.

Thanks