簡體   English   中英

使用NSCharacterSet刪除所有不需要的字符

[英]Removing all non wanted characters using the NSCharacterSet

我想從我的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

創建可變字符集並添加要保留的其他字符。 如果你想在字符串中保留數字,你可能也意味着使用字母數字字符集而不是letterCharacterSet。

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

NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet];

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM