Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace occurrences of two characters with each other in a string

I have a problem where I need to invert two characters within a string. For example, if my string is "a*b/c" and I want to replace occurrences of * with / and / with *. I want the resulting string to be "a/b*c".

Using the method stringByReplacingOccurrenceOfString: doesn't work because I don't want the first round of replacements to affect the second:

string = @"a*b/c";
[string stringByReplacingOccurrencesOfString:@"*" withString:@"/"];
[string stringByReplacingOccurrencesOfString:@"/" withString:@"*"];

This results in "a*b*c", which is not what I want. Does anybody know an efficient way of accomplishing this?

like image 293
Amendale Avatar asked Mar 23 '23 21:03

Amendale


1 Answers

string = @"a*b/c";
[string stringByReplacingOccurrencesOfString:@"*" withString:@"&"];
[string stringByReplacingOccurrencesOfString:@"/" withString:@"*"];
[string stringByReplacingOccurrencesOfString:@"&" withString:@"/"];
like image 64
Sanjay Chaudhry Avatar answered Apr 26 '23 09:04

Sanjay Chaudhry