我想从我的NSString中删除所有不是(数字,字母,来,空格或句点)的字符。
我正在使用NSCharacterSet,但它无法添加到它。我尝试了可变版本添加空格,逗号和句点,但没有成功。
// str is my string
NSCharacterSet *charactersToRemove =
[[ NSCharacterSet letterCharacterSet ] invertedSet ];
NSString *trimmedReplacement =
[[ str componentsSeparatedByCharactersInSet:charactersToRemove ]
componentsJoinedByString:@"" ];
// this removes spaces, periods, and commas too. How do I add in to the character set to keep them
答案 0 :(得分:33)
创建一个可变字符集并添加您想要保留的其他字符。如果你想在字符串中保留数字,你可能也意味着使用字母数字字符集而不是letterCharacterSet。
NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToKeep addCharactersInString:@" ,."];
NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet];
NSString *trimmedReplacement = [[ str componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@"" ];