简体   繁体   English

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

[英]how to replace many occurrences of comma by single comma

Earlier I had string as 1,2,3,,5,6,7 之前我的字符串是1,2,3,,5,6,7

To replace string, I used stringByReplacingOccurrencesOfString:@",," withString:@"," , which gives output as 1,2,3,5,6,7 要替换字符串,我使用了stringByReplacingOccurrencesOfString:@",," withString:@"," ,其输出为1,2,3,5,6,7

Now I have string as below. 现在我有如下字符串。

1,2,3,,,6,7

To replace string, I used stringByReplacingOccurrencesOfString:@",," withString:@"," , which gives output as 1,2,3,,6,7 要替换字符串,我使用了stringByReplacingOccurrencesOfString:@",," withString:@"," ,其输出为1,2,3,,6,7

Is there way where I can replace all double comma by single comma. 有没有办法我可以将所有双逗号替换为单逗号。

I know I can do it using for loop or while loop, but I want to check is there any other way? 我知道我可以使用for循环或while循环来完成此操作,但是我想检查是否还有其他方法?

for (int j=1;j<=100;j++) {
    stringByReplacingOccurrencesOfString:@",," withString:@","]] 
}
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);

This will match any number of , present in the string. 这将匹配任何数量的,目前的字符串中。 It's future proof :) 这是未来的证明:)

Not the perfect solution, but what about this 不是完美的解决方案,但是这怎么办

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM