Remove characters in NSCharacterSet from NSString

cschwarz picture cschwarz · Aug 13, 2010 · Viewed 9k times · Source

I have an NSCharacterSet which contains all the characters I want to remove from my NSString.

How can I do that?

Answer

David picture David · Aug 13, 2010

If you're not too worried about efficiency, a simple way would be [[myString componentsSeparatedByCharactersInSet:myCharacterSet] componentsJoinedByString:@""].

Otherwise, you could run through the characters in a loop, appending ones that weren't in the set onto a new string. If you do it that way, remember to use an NSMutableString for your result as you're building it up.