我试图从字符串中删除所有特殊字符,下面的工作正常,除了它删除单词之间的空格

时间:2021-01-25 19:45:20

Here I am trying to remove all special characters from a string and this working fine except it is removing the spaces between the words as well.I need the spaces in between the words.

在这里,我试图从字符串中删除所有特殊字符,这工作正常,除了它是删除单词之间的空格。我需要在单词之间的空格。

NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];

    dataString = [[dataString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];

1 个解决方案

#1


2  

You can use a NSMutableCharacterSet like in this example:

您可以像在此示例中一样使用NSMutableCharacterSet:

NSMutableCharacterSet * charactersToRemove = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToRemove addCharactersInString:@" "];

NSCharacterSet *newCharactersToRemove = [charactersToRemove invertedSet];

#1


2  

You can use a NSMutableCharacterSet like in this example:

您可以像在此示例中一样使用NSMutableCharacterSet:

NSMutableCharacterSet * charactersToRemove = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToRemove addCharactersInString:@" "];

NSCharacterSet *newCharactersToRemove = [charactersToRemove invertedSet];