Remove Any Character Or Set Of Characters From String Using NSCharacterSet and NSMutableCharacterSet

Although the NSString class has methods such as rangeOfCharacterFromSet: and stringByReplacingOccurrencesOfString:withString:, often times you may need more flexibility than either of these two methods afford.

For example, if you need to remove all occurrences of any character in a set, NSCharacter and NSMutableCharacterSet are the way to go.

Let’s assume you wanted to remove all numbers from the string “99 bottles of beer on the wall”

NSString *str = @"99 bottles of beer on the wall";
NSLog(@"String: %@", str);
 
// Create character set with digits only
NSMutableCharacterSet *characterSet = [NSMutableCharacterSet decimalDigitCharacterSet];
 
// Build array of components using digits as separator
NSArray *arrayOfComponents = [str componentsSeparatedByCharactersInSet:characterSet];
 
// Create string from the array components
NSString *strOutput = [arrayOfComponents componentsJoinedByString:@""];
 
NSLog(@"New string: %@", strOutput);

The output will looks as follows:

String: 99 bottles of beer on the wall
New string: bottles of beer on the wall
Continue reading