Remove spaces from a string

22,375

Solution 1

This can be accomplished with simple string formatting. Here's an example:

NSString *s = @"0800 444 333";
NSString *secondString = [s stringByReplacingOccurrencesOfString:@" " withString:@""];

See the NSString Class Reference for more details and options.

To further simplify, this line can also be written like this:

NSString *s = [@"0800 444 333" stringByReplacingOccurrencesOfString:@" " withString:@""];

Solution 2

if You want to remove white spaces at start and end the you usestringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]string method.

For eg.

NSString *s = @"0800 444 333";
s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

And for removing all spaces answer by @NSPostWhenIdle is enough.

Solution 3

I don't know why, but replacing @" " doesn't work in my case. The solution is easy, just write space as unicode character:

str = [str stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];
Share:
22,375
sefirosu
Author by

sefirosu

...not much to say for now...

Updated on July 05, 2022

Comments

  • sefirosu
    sefirosu almost 2 years
    NSString *s = @"0800 444 333";
    

    As you can see, this string has 2 white-spaces in the middle. My questions is, how do I get rid of them so the string can become:

    s = @"0800444333"
    
  • bummi
    bummi over 9 years
    Could you describe the difference to the accepted answer?