Why doesn't whitespaceAndNewlineCharacterSet remove spaces?

This code MUST clear the phone number, but it is not:

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 a text string (except for the hard path)?

+4
source share
2 answers

try it

 NSCharacterSet *dontWantChar = [NSCharacterSet whitespaceAndNewlineCharacterSet]; NSString *string = [[self.textView.text componentsSeparatedByCharactersInSet:dontWantChar] componentsJoinedByString:@""]; 
+11
source

The documentation for stringByTrimmingCharactersInSet states:

Returns a new line, executed by deleting from both ends that are contained in the specified character set.

In other words, it only removes offensive characters before and after the line with any valid characters. Any โ€œoffensiveโ€ characters remain in the middle of the line, because the trimming method does not apply to this part.

In any case, there are several ways to do what you are trying to do (and @Narayana's answer is good too ... +1 to him / her). My solution would be to set your string s as mutable string and then do:

 [s replaceOccurrencesOfString: @" " withString: @"" options: NSBackwardsSearch range: NSMakeRange( 0, [s length] )]; 
+2
source

Source: https://habr.com/ru/post/1386274/


All Articles