4

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)?

JOM
  • 8,139
  • 6
  • 78
  • 111

2 Answers2

11

Try this

NSCharacterSet *dontWantChar = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *string = [[self.textView.text componentsSeparatedByCharactersInSet:dontWantChar] componentsJoinedByString:@""];
pkamb
  • 33,281
  • 23
  • 160
  • 191
Narayana Rao Routhu
  • 6,303
  • 27
  • 42
  • Perfect, thanx! Found another solution, but your answer was correct for the question :) – JOM Dec 14 '11 at 09:45
2

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] )];
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Documentation, what documentation? Not used to work in documented environments... so really appreciate the tip! – JOM Dec 14 '11 at 09:46
  • You'll find http://developer.apple.com/iphone is a very very fine resource. And I did link up the documentation for `stringByTrimmingCharactersInSet` for you up there. – Michael Dautermann Dec 14 '11 at 09:47