简体   繁体   English

从NSString中删除不允许的字符

[英]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? 为什么invertedSet不起作用?

One more weird thing here. 这里还有一件奇怪的事情。 If I removed the invertedSet part like 如果我删除invertedSet部分

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. stringByTrimmingCharactersInSet:仅删除字符串开头和结尾的出现。 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-. stringByTrimmingCharactersInSet仅删除字符串末尾的字符,结果为-222-。 You have to do a little trick to remove all chars in the set 您必须做一些技巧来删除集合中的所有字符

 NSString *newString = [[origString componentsSeparatedByCharactersInSet:
            [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] 
            componentsJoinedByString:@""];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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