Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to remove the formatting from a phone number to only get the digits?

Tags:

cocoa

iphone

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;
like image 392
Mack Avatar asked Sep 27 '10 21:09

Mack


3 Answers

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

like image 65
kba Avatar answered Sep 28 '22 04:09

kba


Dupe of 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:@""];
like image 34
zpasternack Avatar answered Sep 28 '22 04:09

zpasternack


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];
like image 33
dreamlax Avatar answered Sep 28 '22 03:09

dreamlax