Cocoa Tutorial: Strip Non-Alphanumeric Characters from an NSString

Let’s say you have an NSString that contains both alphanumeric and non-alphanumeric characters and you want to strip the non-alphanumeric characters out of it. The hard way is to manually go through, character-by-character, and put the character in a new string if it matches certain criteria. But why do it the hard way?

Apple provides a class that we can use for this to great effect: NSCharacterSet. We want alphanumeric characters, so we can create a character set of the characters we want using this method:

NSCharacterSet *alphanumericSet = [ NSCharacterSet alphanumericCharacterSet ];

Now we have a character set like we want. We just need a way to turn our string into a string that contains only those characters. Unfortunately, the closest thing in NSString’s implementation is the -stringByTrimmingCharactersInSet: method. But that seems to do the opposite of what we want. Fortunately NSCharacterSet has our back here. We can use the -invertedSet method. So here is our final code:

NSString *beginningString = @"Some string with non-alphanumeric characters. !@#$%^&*()";
NSCharacterSet *nonalphanumericSet = [[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];
NSString *endingString = [ beginningString stringByTrimmingCharactersInSet:nonalphanumericSet ];

In this example, endingString will be equal to “Somestringwithnonalphanumericcharacters”.

UPDATE: As it turns out, this only works if the non-alphanumeric characters are at the beginning or end of the NSString. Whoops.