从[NSCharacterSet letterCharacterSet] invertedSet]手动排除一些符号

时间:2011-09-02 13:35:11

标签: objective-c ios nsstring

以下代码将删除myString中的所有符号。是否有一种最简单的方法可以使某些独占符号(比如')被删除而仍能使用此代码?

myString = [[myString componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];

1 个答案:

答案 0 :(得分:3)

您需要创建一个可变副本,然后使用NSMutableCharacterSet进行更改。

NSMutableCharacterSet *mcs = [[[NSCharacterSet letterCharacterSet] invertedSet] mutableCopy];
[mcs removeCharactersInString:@"<characters you want excluded>"];

myString = [[myString componentsSeparatedByCharactersInSet:mcs] componentsJoinedByString:@""];

[mcs release];