如何用单个逗号替换多次出现的逗号

时间:2014-05-19 09:32:15

标签: ios objective-c replace

之前我的字符串为1,2,3,,5,6,7

要替换字符串,我使用stringByReplacingOccurrencesOfString:@",," withString:@",",输出为1,2,3,5,6,7

现在我有以下字符串。

1,2,3,,,6,7

要替换字符串,我使用stringByReplacingOccurrencesOfString:@",," withString:@",",输出为1,2,3,,6,7

我可以通过单个逗号替换所有双逗号。

我知道我可以使用for循环或while循环,但我想检查是否有其他方法?

for (int j=1;j<=100;j++) {
    stringByReplacingOccurrencesOfString:@",," withString:@","]] 
}

2 个答案:

答案 0 :(得分:5)

NSString *string = @"1,2,3,,,6,7";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@",{2,}" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@","];
NSLog(@"%@", modifiedString);

这将匹配字符串中存在的任意数量的,。这是未来的证明:)

答案 1 :(得分:2)

不是完美的解决方案,但是这个呢?

NSString *string = @"1,2,3,,,6,7";
NSMutableArray *array =[[string componentsSeparatedByString:@","] mutableCopy];
[array removeObject:@""];

NSLog(@"%@",[array componentsJoinedByString:@","]);