Search code examples
cocoacocoa-touchnsstringnscharacterset

Strip Non-Alphanumeric Characters from an NSString


I'm looking for a quick and easy way to strip non-alphanumeric characters from an NSString. Probably something using an NSCharacterSet, but I'm tired and nothing seems to return a string containing only the alphanumeric characters in a string.


Solution

  • We can do this by splitting and then joining. Requires OS X 10.5+ for the componentsSeparatedByCharactersInSet:

    NSCharacterSet *charactersToRemove = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    NSString *strippedReplacement = [[someString componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""];