2011-09-15 25 views
1

我想將字符串轉換爲電話號碼格式。例如,我有我有價值的字符串「456897012」。現在我想將它轉換爲電話號碼格式,如(456)897-012。 那麼過程是什麼?我怎樣才能做到這一點?如何在電話號碼格式中轉換字符串?客觀c

+4

[你嘗試過什麼?](http://mattgemmell.com/2008/12/08/what-have-you-tried) –

+0

@布賴恩·羅奇人輝煌的鏈接,我從來沒有看到過。 ..一書籤.. – Krishnabhadra

+0

不是一個直接的答案,但將幫助你..http://stackoverflow.com/questions/665111/nsnumberformatter-to-format-us-telephone-numbers – Krishnabhadra

回答

1

假設你有oldPhone

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

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

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

還沒有測試它。

希望幫助

+1

C!= Objective C –

+0

哇......我忘記了「客觀」,它的好,將它轉換爲客觀的c:P 邏輯是一樣的:P – Sanosay

3

像這樣的東西應該工作了我猜;

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);