我有类似123-123-1234的字符串,所以我想将字符串转换为这种格式 (123)123-1234所以任何想法来开发这个功能。
提前致谢。
答案 0 :(得分:5)
我认为是这样的:
NSString *list = @"123-123-1234";
NSArray *listItems = [list componentsSeparatedByString:@"-"];
NSString *result = [NSString stringWithFormat:@"(%@) %@-%@", [listItem objectAtIndex:0], [listItem objectAtIndex:1], [listItem objectAtIndex:2]];
答案 1 :(得分:1)
测试代码:100%工作
NSString *inputString=@"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);
<强>输出:强> outputString是:(123)123-1234
动态溶剂:
注意:如果你的ur字符串有更多破折号,那么使用objectAtIndex编号为0,1,2,....的所有内容都很难编码。
此外,如果它有意想不到的长度,它将崩溃
所以这是这个
的解决方案NSString *inputString=@"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
答案 2 :(得分: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);
答案 3 :(得分:1)
NSString * str = @“123-123-1234”;
NSArray * arrForDate = [str componentsSeparatedByString:@“ - ”];
NSString * str1 = [NSString stringWithFormat:@“(%@)%@ - %@”,[arrForDate objectAtIndex:0],[arrForDate objectAtIndex:1],[arrForDate objectAtIndex:2]];
NSLog(@“str1%@”,str1);
答案 4 :(得分:0)
NSString * list = @“ 123-123-1234”; NSArray * listItems = [列出componentsSeparatedByString:@“-”]; NSString * result = [NSString stringWithFormat:@“(%@)%@-%@”,[listItem objectAtIndex:0],[listItem objectAtIndex:1],[listItem objectAtIndex:2]];