I have an NSString
that holds something like this:
4434332124
How can I make that into something like this?
443-433-2124
I have an NSString
that holds something like this:
4434332124
How can I make that into something like this?
443-433-2124
This can be done in only two lines just use NSString's stringWithFormat method and chop up the phone number into individual substrings and glue the whole thing together in your format string. Something like this:
NSString *sPhone = @"4434332124";
NSString *formatted = [NSString stringWithFormat: @"%@-%@-%@", [sPhone substringWithRange:NSMakeRange(A,B)],[sPhone substringWithRange:NSMakeRange(B,C)],
[sPhone substringWithRange:NSMakeRange(C,D)]];
EDIT: Working Code
NSString *formatted = [NSString stringWithFormat: @"%@-%@-%@", [sPhone substringWithRange:NSMakeRange(0,3)],[sPhone substringWithRange:NSMakeRange(3,3)],
[sPhone substringWithRange:NSMakeRange(6,4)]];
If you want to just do a simple quick replacement on what you are sure is a 10 digit number then try this regex example (iOS >= 3.2).
NSString *tenDigitNumber = @"5554449999";
tenDigitNumber = [tenDigitNumber stringByReplacingOccurrencesOfString:@"(\\d{3})(\\d{3})(\\d{4})"
withString:@"$1-$2-$3"
options:NSRegularExpressionSearch
range:NSMakeRange(0, [tenDigitNumber length])];
NSLog(@"%@", tenDigitNumber);
Not as pretty as trying to do something with NSFormatter (though unless you subclass it I didn't see an obvious way to get it to do something like phone numbers) but you could do this:
NSString* newString = [NSString stringWithFormat:@"%c%c%c-%c%c%c-%c%c%c%c" [phoneNumber characterAtIndex:0],
[phoneNumber characterAtIndex:1],
[phoneNumber characterAtIndex:2],
[phoneNumber characterAtIndex:3],
[phoneNumber characterAtIndex:4],
[phoneNumber characterAtIndex:5],
[phoneNumber characterAtIndex:6],
[phoneNumber characterAtIndex:7],
[phoneNumber characterAtIndex:8],
[phoneNumber characterAtIndex:9]];
#import <Foundation/Foundation.h>
static NSString * const theInString = @"4434332124";
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
const char * theUniChar = theInString.UTF8String;
NSMurableString * theResult = nil;
for( int i = 0, c = (int)strlen(theUniChar); i < c; i+=2 )
{
char thePart[4];
sscanf( theUniChar + i, "%3s", &thePart );
if( theResult == nil )
theResult = [NSMutableString string];
else
[theResult appendFormate:@"-%3s",thePart];
}
printf( "%@\n", theResult );
[pool drain];
return 0;
}