Search code examples
objective-cnscharacterset

Remove unallowed characters from NSString


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.


Solution

  • 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:@""];
    }