我有類似123-123-1234的字符串,所以我想將字符串轉換爲這種格式 (123)123-1234所以任何想法來開發這個功能。iPhone:將NSString 123-123-1234轉換爲(123)123-1234
在此先感謝。
我有類似123-123-1234的字符串,所以我想將字符串轉換爲這種格式 (123)123-1234所以任何想法來開發這個功能。iPhone:將NSString 123-123-1234轉換爲(123)123-1234
在此先感謝。
我覺得是這樣的:
NSString *list = @"123-123-1234";
NSArray *listItems = [list componentsSeparatedByString:@"-"];
NSString *result = [NSString stringWithFormat:@"(%@) %@-%@", [listItem objectAtIndex:0], [listItem objectAtIndex:1], [listItem objectAtIndex:2]];
測試的代碼:100%WORKS
NSString *[email protected]"123-123-1234";
NSArray *TotalString=[inputString componentsSeparatedByString:@"-"];
NSString *outputString = [NSString stringWithFormat:@"(%@) %@-%@",[TotalString objectAtIndex:0],[TotalString objectAtIndex:1],[TotalString objectAtIndex:2]];
NSLog(@"outputString is : %@ \n\n",outputString);
OUTPUT: outputString是:(123)123-1234
對於動態Sollution:
注:如果u有更多的破折號與UR串那麼它真的很難代碼一切與objectAtIndex用數字0,1,2,......
而且它會崩潰,如果它有意想不到的長度
所以這裏是這個
NSString *[email protected]"123-123-1234";
NSArray *TotalString=[inputString componentsSeparatedByString:@"-"];
NSMutableString *outputString=[NSMutableString string];
for (NSMutableString *obj in TotalString) {
if ([TotalString objectAtIndex:0] == obj && [outputString length]<=0) {
outputString=[[outputString stringByAppendingFormat:@"(%@)",obj] mutableCopy];
}
else if ([TotalString objectAtIndex:1] == obj) {
outputString=[[outputString stringByAppendingFormat:@"%@%@",@" ",obj] mutableCopy];
}
else {
outputString=[[outputString stringByAppendingFormat:@"-%@",obj] mutableCopy];
}
}
輸出的解決方案: outputString是:(123)123-1234
NSString * original = @"123-123-1234";
NSArray * components = [original componentsSeparatedByString:@"-"];
NSString * first = [NSString stringWithFormat:@"(%@)",[components objectAtIndex:0] ];
NSString * second = [NSString stringWithFormat:@"%@-%@",[components objectAtIndex:1],[components objectAtIndex:2]];
NSString * finalString = [NSString stringWithFormat:@"%@%@",first,second];
NSLog(@"Final Result = %@",finalString);
非常感謝bharat –
的NSString * STR = @ 「123-123-1234」;
NSArray * arrForDate = [str componentsSeparatedByString:@「 - 」];
的NSString * STR1 = [NSString的stringWithFormat:@ 「(%@)%@ - @%」,[arrForDate objectAtIndex:0],[arrForDate objectAtIndex:1],[arrForDate objectAtIndex:2]]; (@「str1%@」,str1);
U FORGOT TO - IN UR輸出格式 –
非常感謝applevijay –