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"
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.
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:@""];
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.
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:@""];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With