是否有一种干净的方法来获取仅包含允许字符的字符串?
例如:
NSString* myStr = @"a5&/Öñ33";
NSString* allowedChars = @"abcdefghijklmnopqrstuvwxyz0123456789";
NSString* result = [myStr stringWIthAllowedChrs:allowedChars];
结果现在应为@"a533"
;
答案 0 :(得分:6)
这不是最干净的,但您可以使用字符集分隔字符串,然后使用空字符串组合生成的数组。
// Create a character set with every character not in allowedChars
NSCharacterSet *charSet = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
// Split the original string at any occurrence of those characters
NSArray *splitString = [myStr componentsSeparatedByCharactersInSet:charSet];
// Combine the result into a string
NSString *result = [splitString componentsJoinedByString:@""];
答案 1 :(得分:3)
简单易用的定制和理解方法:
NSString* myStr = @"a5&/Öñ33";
NSString* allowedChars = @"abcdefghijklmnopqrstuvwxyz0123456789";
NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:allowedChars] invertedSet];
NSString *result = myStr;
NSRange range = [result rangeOfCharacterFromSet:set];
while (range.location != NSNotFound)
{
result = [result stringByReplacingCharactersInRange:range withString:@""];
range = [result rangeOfCharacterFromSet:set];
}
NSLog(@"%@", result);
答案 2 :(得分:2)
最简单的一个 -
NSString* result = @"";
for(NSUInteger i = 0; i < [myStr length]; i++)
{
unichar charArr[1] = {[myStr characterAtIndex:i]};
NSString* charString = [NSString stringWithCharacters:charArr length:1];
if([allowedChars rangeOfString:charString].location != NSNotFound)
result = [result stringByAppendingString:charString];
}
return result;