Created
May 24, 2013 22:17
-
-
Save NicholasPeterson/5646871 to your computer and use it in GitHub Desktop.
Basic phone number formatting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSString *)normalizedPhoneNumber { | |
NSString *normalString = self; | |
if (!self) return nil; | |
normalString = [normalString lowercaseString]; | |
NSCharacterSet *normalizationSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"] invertedSet]; | |
normalString = [[[normalString componentsSeparatedByCharactersInSet:normalizationSet] componentsJoinedByString:@""] uppercaseString]; | |
NSMutableString *phoneNumber = [[normalString mutableCopy] autorelease]; | |
char tmpChar; | |
BOOL elevenPlus = NO; | |
unsigned int offset = 0; | |
switch (normalString.length) { | |
case 13: | |
offset ++; | |
case 12: | |
offset ++; | |
case 11: | |
tmpChar = [phoneNumber characterAtIndex:0+offset]; | |
elevenPlus = YES; | |
[phoneNumber insertString:@" " atIndex:1+offset]; | |
offset += 2; | |
case 10: | |
tmpChar = [phoneNumber characterAtIndex:0+offset]; | |
[phoneNumber insertString:@"(" atIndex:0+offset]; | |
[phoneNumber insertString:@") " atIndex:4+offset]; | |
offset += 6; | |
case 7: | |
tmpChar = [phoneNumber characterAtIndex:0+offset]; | |
[phoneNumber insertString:@"-" atIndex:3+offset]; | |
break; | |
default: | |
[phoneNumber setString:self]; | |
elevenPlus = NO; | |
break; | |
} | |
if (elevenPlus) [phoneNumber insertString:@"+" atIndex:0]; | |
return phoneNumber; | |
} |
Author
NicholasPeterson
commented
May 24, 2013
- INPUT, OUTPUT
- 00-000-000, 00-000-000
- 000-000-0000, (000) 000-0000
- 0000000, 000-0000
- 00-000-000-0000, +00 (000) 000-0000
- 0000000000, (000) 000-0000
- 000000000000, +00 (000) 000-0000
- 1800comcast, +1 (800) COM-CAST
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment