Skip to content

Instantly share code, notes, and snippets.

@NicholasPeterson
Created May 24, 2013 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicholasPeterson/5646871 to your computer and use it in GitHub Desktop.
Save NicholasPeterson/5646871 to your computer and use it in GitHub Desktop.
Basic phone number formatting
- (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;
}
@NicholasPeterson
Copy link
Author

  • 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