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)?
Try this
NSCharacterSet *dontWantChar = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *string = [[self.textView.text componentsSeparatedByCharactersInSet:dontWantChar] componentsJoinedByString:@""];
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] )];
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