简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM