Fahim Parkar
Fahim Parkar

Reputation: 31637

how to replace many occurrences of comma by single comma

Earlier I had string as 1,2,3,,5,6,7

To replace string, I used stringByReplacingOccurrencesOfString:@",," withString:@",", which gives output as 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

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

Upvotes: 1

Views: 123

Answers (2)

mohamedrias
mohamedrias

Reputation: 18566

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 :)

Upvotes: 5

Anil Varghese
Anil Varghese

Reputation: 42977

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:@","]);

Upvotes: 2

Related Questions