I'm new to Objective-C, but experienced in other higher languages. I want to normalize a string by removing all non-numeric characters. In other words given the input string "206-555-1212" the normalized result should be "2065551212". The code snippet below works, but given my experience in other languages that seems like overkill. Is there a better way to do it?
EDIT: The input strings "(206) 555-1212", "206.555.1212", "206 555 1212", etc. should also return the same normalized result.
NSString * normalize(NSString * number)
{
NSString *normalizedNumber = @"";
NSString *tmpString = nil;
NSRange searchRange;
NSRange resultRange;
searchRange.location = 0;
searchRange.length = number.length;
while (0 < searchRange.length)
{
resultRange = [number rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]
options:NSLiteralSearch
range:searchRange];
tmpString = [number substringWithRange:resultRange];
normalizedNumber = [normalizedNumber stringByAppendingString:tmpString];
searchRange.location = resultRange.location + resultRange.length;
searchRange.length = number.length - searchRange.location;
}
return normalizedNumber;
}