Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 223
Raju Avatar asked May 29 '09 12:05

Raju


3 Answers

You could use:

NSString *stringWithoutSpaces = [myString 
   stringByReplacingOccurrencesOfString:@" " withString:@""];
like image 189
Tom Jefferys Avatar answered Nov 15 '22 06:11

Tom Jefferys


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:@""];
like image 22
Jim Dovey Avatar answered Nov 15 '22 06:11

Jim Dovey


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.

like image 11
visakh7 Avatar answered Nov 15 '22 04:11

visakh7