Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces from a string

Tags:

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"
like image 734
sefirosu Avatar asked Aug 25 '12 08:08

sefirosu


People also ask

How do you remove spaces from a string in Java?

Java has inbuilt methods to remove the whitespaces from the string, whether leading, trailing, both, or all. trim() method removes the leading and trailing spaces present in the string. strip() method removes the leading and trailing spaces present in the string.


3 Answers

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:@""];
like image 164
Mick MacCallum Avatar answered Nov 02 '22 03:11

Mick MacCallum


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.

like image 21
Ravi Sharma Avatar answered Nov 02 '22 05:11

Ravi Sharma


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:@""];
like image 26
Boomerange Avatar answered Nov 02 '22 04:11

Boomerange