[ACCEPTED]-Remove characters from NSString?-nsstring

Accepted answer
Score: 283

You could use:

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

0

Score: 80

If you want to support more than one space 2 at a time, or support any whitespace, you 1 can do this:

NSString* noSpaces =
    [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                           componentsJoinedByString:@""];
Score: 11

Taken from NSString

stringByReplacingOccurrencesOfString:withString:

Returns a new string in which 5 all occurrences of a target string in the 4 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 3 Value

A new string in which all occurrences 2 of target in the receiver are replaced by 1 replacement.

Score: 10

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

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

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

Thanks

Score: 6

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

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

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

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

You can try this

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

Hope this will help you 1 out.

More Related questions