0

I want to allow only specific characters for a string.

Here's what I've tried.

NSString *mdn = @"010-222-1111";

NSCharacterSet *allowedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"+0123456789"];
NSString *trimmed = [mdn stringByTrimmingCharactersInSet:[allowedCharacterSet invertedSet]];
NSString *replaced = [mdn stringByReplacingOccurrencesOfString:@"-" withString:@""];

The result of above code is as below. The result of replaced is what I want.

trimmed : 010-222-1111
replaced : 0102221111

What am I missing here? Why doesn't invertedSet work?

One more weird thing here. If I removed the invertedSet part like

NSString *trimmed = [mdn stringByTrimmingCharactersInSet:allowedCharacterSet];

The result is

trimmed : -222-

I have no idea what makes this result.

Ryan
  • 4,799
  • 1
  • 29
  • 56
  • Also check out http://stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstring – Arkku Feb 25 '15 at 07:19

2 Answers2

3

stringByTrimmingCharactersInSet: only removes occurrences in the beginning and the end of the string. That´s why when you take inverted set, no feasible characters are found in the beginning and end of the string and thus aren't removed either.

A solution would be:

- (NSString *)stringByRemovingCharacters:(NSString*)str inSet:(NSCharacterSet *)characterSet {
    return [[str componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
}
Widerberg
  • 1,118
  • 1
  • 10
  • 24
0

stringByTrimmingCharactersInSet is only removing chars at the end and the beginning of the string, which results in -222-. You have to do a little trick to remove all chars in the set

 NSString *newString = [[origString componentsSeparatedByCharactersInSet:
            [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] 
            componentsJoinedByString:@""];
Thallius
  • 2,482
  • 2
  • 18
  • 36