Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why whitespaceAndNewlineCharacterSet doesn't remove spaces?

This code SHOULD clean phone number, but it doesn't:

NSLog(@"%@", self.textView.text);
// Output +358 40 111 1111
NSString *s = [self.textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", s);
// Output +358 40 111 1111

Any ideas what is wrong? Any other ways to remove whitespacish characters from text string (except the hard way)?

like image 209
JOM Avatar asked Dec 12 '22 07:12

JOM


2 Answers

Try this

NSCharacterSet *dontWantChar = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *string = [[self.textView.text componentsSeparatedByCharactersInSet:dontWantChar] componentsJoinedByString:@""];
like image 122
Narayana Avatar answered Mar 15 '23 01:03

Narayana


The documentation for stringByTrimmingCharactersInSet says:

Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

In other words, it only removes the offending characters from before and after the string any valid characters. Any "offending" characters are left in the middle of the string because the trim method doesn't touch that part.

Anyways, there are a few ways to do the thing you're trying to do (and @Narayana's answer is good on this, too... +1 to him/her). My solution would be to set your string s to be a mutable string and then do:

[s replaceOccurrencesOfString: @" " withString: @"" options: NSBackwardsSearch range: NSMakeRange( 0, [s length] )];
like image 29
Michael Dautermann Avatar answered Mar 15 '23 01:03

Michael Dautermann