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;
You could use a RegEx-replacement that replaces [\D]
with nothing.
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:@""];
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With