You can use regular expressions:
NSMutableString *str = [@"Hello $World$, foo $bar$." mutableCopy];
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"\\$([^$]*)\\$"
options:0
error:NULL];
[regex replaceMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:@"[$1]"];
NSLog(@"%@", str);
// Output:
// Hello [World], foo [bar].
The pattern @"\\$([^$]*)\\$"
searches for
$<zero_or_more_characters_which_are_not_a_dollarsign>$
and all occurrences are then replaced by [...]
. The pattern contains so many backslashes because the $
must be escaped in the regular expression pattern.
There is also stringByReplacingMatchesInString
if you want to create a new string instead of modifying the original string.