What is a good way to remove formatting from a phone number in order to get only numbers?

Is there a better or shorter way to mark all non-digital characters with Objective-C on 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; 
+6
iphone cocoa
source share
4 answers

You can use the RegEx replacement, which replaces [\D] nothing.

+4
source share

Dupe Remove all but numbers from NSString

The accepted answer implies the use of NSScanner, which seems difficult for such a simple task. I stick with what you have (although someone from another thread has suggested a more compact version, if so:

 NSString *digits = [[formattedNumber componentsSeparatedByCharactersInSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""]; 
+3
source share

Phone numbers can contain asterisks and number signs ( * and # ), and can start with + . Recommendation ITU-T Recommendation E-123 recommends using the + symbol to indicate that the number is an international number, and also serve as a reminder that the international dialing sequence for a particular country should be used instead.

You cannot type spaces, hyphens, or parentheses, so they do not matter in the phone number. To cut out all useless characters, you must delete all characters not in the decimal character set except * and # , as well as any + not found at the beginning of the phone number.

As far as I know, there is no standardized or recommended way to represent manual extensions (some use x , some use ext , some use E ). Although, I have not come across a manual extension for 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]; 
+3
source share

You can do something like this:

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

Noting the 0xA3 comment above, you can use another NSCharacterSet, which includes + and other non-digital numbers that are valid in phone numbers.

0
source share

All Articles