tags:

views:

74

answers:

4

Is there a better or shorter way of striping out all the non-digit characters with Objective-C on the iPhone?

NSString * formattedNumber = @"(123) 555-1234";
NSCharacterSet * nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

NSString * digits;
NSArray * parts = [formattedNumber componentsSeparatedByCharactersInSet:nonDigits];
if ( [parts count] > 1 ) {
    digits = [parts componentsJoinedByString:@""];
} else {
    digits = [parts objectAtIndex:0];
}
return digits;
+3  A: 

You could use a RegEx-replacement that replaces [\D] with nothing.

Kristian Antonsen
A: 

You could do something like this:

NSString *digits = [[formattedNumber componentsSeparatedByCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]] componentsJoinedByString:@""];

Noting 0xA3's comment above, you could optionally use a different NSCharacterSet that includes + and other non-digits that are valid in phone numbers.

GregInYEG
+1  A: 

Dupe of http://stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstring

The accepted answer there involves using NSScanner, which seems heavy-handed for such a simple task. I'd stick with what you have there (though someone in the other thread suggested a more compact version if it, thus:

NSString *digits = [[formattedNumber componentsSeparatedByCharactersInSet:
                        [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] 
                       componentsJoinedByString:@""];
zpasternack
Thanks. Yes, I was wondering whether the if statement was adding any value.
Mack
+2  A: 

Phone numbers can contain asterisks and number signs (* and #), and may start with a +. The ITU-T E-123 Recommandation recommends that the + symbol be used to indicate that the number is an international number and also to serve as a reminder that the country-specific international dialling sequence must be used in place of it.

Spaces, hyphens and parentheses cannot be dialled so they do not have any significance in a phone number. In order to strip out all useless symbols, you should remove all characters not in the decimal character set, except * and #, and also any + not found at the start of the phone number.

To my knowledge, there is no standardised or recommended way to represent manual extensions (some use x, some use ext, some use E). Although, I have not encountered a manual extension in a long time.

NSUInteger inLength, outLength, i;
NSString *formatted = @"(123) 555-5555";

inLength = [formatted length];
unichar result[inLength];

for (i = 0, outLength = 0; i < inLength; i++)
{
    unichar thisChar = [formatted characterAtIndex:i];

    if (iswdigit(thisChar) || thisChar == '*' || thisChar == '#')
        result[outLength++] = thisChar;   // diallable number or symbol
    else if (i == 0 && thisChar == '+')
        result[outLength++] = thisChar;   // international prefix
}

NSString *stripped = [NSString stringWithCharacters:result length:outLength];
dreamlax