Friday, January 14, 2011

Objective C: Remove certain characters from NSString

Sometimes when you work in Xcode in the Cocoa Framework you want to filter a NSString so that only certain characters are left. That can be numbers or letters or special characters. Following code snippet can do that for you.

//the String with the original text
NSString *unfilteredString = @"The sum of 1 + 2 = 3.";
//initialize a string that will hold the result
NSMutableString *resultString = [NSMutableString stringWithCapacity:unfilteredString.length];
NSScanner *scanner = [NSScanner scannerWithString:unfilteredString];
//define the allowed characters, here only numbers from one to three, equal and plus
NSCharacterSet *allowedChars = [NSCharacterSet characterSetWithCharactersInString:@"123+="];
while ([scanner isAtEnd] == NO) {
 NSString *buffer;
 if ([scanner scanCharactersFromSet:allowedChars intoString:&buffer]) {
  [resultString appendString:buffer];     
 } else {
  [scanner setScanLocation:([scanner scanLocation] + 1)];
//Print out the result String, will be 1+2=3   
NSLog (@"Result: %@", resultString);


Anonymous said...

Much simpler solution:

NSString *unfilteredString = @"The sum of 1 + 2 = 3.";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"123+="] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", resultString);

Post a Comment