2012-03-12 62 views
10

我想從我的NSString中刪除不是(數字,字母,來,空格或句點)的所有字符。使用NSCharacterSet刪除所有不需要的字符

我正在使用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 

回答

32

創建一個可變字符集並添加要保留的其他字符。如果你想讓字符串中的數字也可以用字母數字字符集代替letterCharacterSet。

NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet]; 
[charactersToKeep addCharactersInString:@" ,."]; 

NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet]; 

NSString *trimmedReplacement = [[ str componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@"" ]; 
+0

使用不變字符集的反轉比反轉可變字符集要有效得多。 – 2017-06-30 10:04:39

相關問題