0

I want to convert string into phone number format. For example I have string in which I have value, "456897012". Now I want to convert it in phone number format like as (456)897-012. So what is process for that? How can I do that?

rptwsthi
  • 10,094
  • 10
  • 68
  • 109
iRam11
  • 309
  • 4
  • 16
  • 4
    [What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried) – Brian Roach Sep 15 '11 at 03:36
  • @Brian Roach Man brilliant link, I never seen that before..one to bookmark.. – Krishnabhadra Sep 15 '11 at 03:39
  • Not a direct answer, but will help you..http://stackoverflow.com/questions/665111/nsnumberformatter-to-format-us-telephone-numbers – Krishnabhadra Sep 15 '11 at 03:41
  • I have the exact same problem. While we can code this ourself, there should be a standard code for this common problem. Not sure why the downvote. – user4951 Nov 07 '12 at 04:25
  • 1
    This question is NOT ambiguous. It's not vague, incomplete or overly broad. Yes OP is lazy. But ambiguous he is not. C'mon guys. – user4951 Nov 20 '12 at 07:15

2 Answers2

3

Something like this should work out I guess;

NSString *unformatted = @"5129876985";
NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)], 
                             [unformatted substringWithRange:NSMakeRange(3, 3)], 
                             [unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];

NSString *formattedString = [NSString stringWithFormat:@"(%@)%@-%@", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
NSLog(@"Formatted Phone Number: %@", formattedString);
Madhu
  • 2,429
  • 16
  • 31
1

Ok

Suppose you have the oldPhone

[oldPhone insertString: @"(" atIndex: 0];

[oldPhone insertString: @")" atIndex: 4];

[oldPhone insertString: @"-" atIndex: 9];

Have not test it.

Hope that helps

Sanosay
  • 536
  • 5
  • 18