使用 anNSScanner
在字符串中移动并替换找到的每个字符。这样一来,所有的替换都在一次传球中完成,而且你永远不会看两次位置。
NSMutableString * fixedUpString = [NSMutableString string];
NSScanner * scanner = [NSScanner scannerWithString:origString];
NSCharacterSet * subCharacters = [NSCharacterSet characterSetWithCharactersInString:@"*/"];
while( ![scanner isAtEnd] ){
// Pick up other characters.
NSString * collector;
if( [scanner scanUpToCharactersInSet:subCharacters intoString:&collector] ){
[fixedUpString appendString:collector];
}
// This can easily be generalized with a loop over a mapping from
// found characters to substitutions
// Check which one we found
if( [scanner scanString:@"*" intoString:nil] ){
// Append the appropriate substitution.
[fixedUpString appendString:@"/"];
}
else /* if( [scanner scanString:@"/" intoString:nil] ) */ {
[fixedUpString appendString:@"*"];
}
}
fixedUpString
现在包含替换的内容。
正如我在评论中指出的那样,这可以很容易地推广到任意数量的替换:
NSDictionary * substitutions = @{ @"a" : @"z", @"b" : @"y", ... };
NSCharacterSet * keyChars = [NSCharacterSet characterSetWithCharactersInString:[[substitutions allKeys] componentsJoinedByString:@""]];
...
// Check which one we found
for( NSString * keyChar in [substitutions allKeys] ){
if( [scanner scanString:keyChar intoString:nil ){
[fixedUpString appendString:substitutions[keyChar]];
break;
}
}