Created
December 3, 2008 23:01
-
-
Save sbrocket/31745 to your computer and use it in GitHub Desktop.
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
@implementation NSString (ContactExtension) | |
- (NSString*)stringFormattedAsPhoneNumber { | |
NSMutableString *newString = nil; | |
BOOL prependPlus = NO; | |
if (!self) | |
return nil; | |
if ([self characterAtIndex:0] == '+') | |
prependPlus = YES; | |
unsigned len = self.length; | |
NSCharacterSet *numericSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; | |
newString = [NSMutableString string]; | |
NSRange range = NSMakeRange(0, 0), tempRange; | |
while (NSMaxRange(range) <= len) { | |
tempRange = [self rangeOfCharacterFromSet:numericSet options:NSLiteralSearch range:NSMakeRange(NSMaxRange(range), len - NSMaxRange(range))]; | |
if (NSMaxRange(range) == tempRange.location) { | |
range.length += tempRange.length; | |
} else { | |
[newString appendString:[self substringWithRange:range]]; | |
range = tempRange; | |
} | |
} | |
char tmpChar; | |
unsigned int offset = 0; | |
switch (newString.length) { | |
case 11: | |
tmpChar = [newString characterAtIndex:0+offset]; | |
if (tmpChar != '1') { [newString setString:self]; prependPlus = NO; break; } | |
[newString insertString:@" " atIndex:1]; | |
offset += 2; | |
case 10: | |
tmpChar = [newString characterAtIndex:0+offset]; | |
if (tmpChar == '0' || tmpChar == '1') { [newString setString:self]; prependPlus = NO; break; } | |
[newString insertString:@"(" atIndex:0+offset]; | |
[newString insertString:@") " atIndex:4+offset]; | |
offset += 6; | |
case 7: | |
tmpChar = [newString characterAtIndex:0+offset]; | |
if (tmpChar == '0' || tmpChar == '1') { [newString setString:self]; prependPlus = NO; break; } | |
[newString insertString:@"-" atIndex:3+offset]; | |
break; | |
default: | |
// Non-standard number format - use the original string | |
[newString setString:self]; | |
prependPlus = NO; | |
break; | |
} | |
if (prependPlus) | |
[newString insertString:@"+" atIndex:0]; | |
return newString; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment