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:@""];
Comments
-
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 over 9 yearsCould you describe the difference to the accepted answer?