2011-09-12 40 views

回答

5

我覺得是這樣的:

NSString *list = @"123-123-1234"; 
NSArray *listItems = [list componentsSeparatedByString:@"-"]; 
NSString *result = [NSString stringWithFormat:@"(%@) %@-%@", [listItem objectAtIndex:0], [listItem objectAtIndex:1], [listItem objectAtIndex:2]]; 
+0

U FORGOT TO - IN UR輸出格式 –

+0

非常感謝applevijay –

1

測試的代碼: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

1
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); 
+0

非常感謝bharat –

1

的NSString * STR = @ 「123-123-1234」;

NSArray * arrForDate = [str componentsSeparatedByString:@「 - 」];

的NSString * STR1 = [NSString的stringWithFormat:@ 「(%@)%@ - @%」,[arrForDate objectAtIndex:0],[arrForDate objectAtIndex:1],[arrForDate objectAtIndex:2]]; (@「str1%@」,str1);