替换字符串中的字符对我来说不起作用

时间:2013-09-27 08:47:11

标签: objective-c

我有NSString chars,我以某种方式构建,而不是替换它的char,所以我这样做:

[chars stringByReplacingOccurrencesOfString:[self convertDecimalToChar:num] withString:[self convertDecimalToChar:num+1]];

如果我打印:

NSLog(@"CHAR:%@ and look for:%@ replace with:%@",chars,[self convertDecimalToChar:num],[self convertDecimalToChar:num+1]);

我可以看到:U U V,所以他必须用V替换U,但它仍然是U ..

我可以在这里错过吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

您应该将返回值分配给NSString

NSString *replaced = [chars stringByReplacingOccurrencesOfString:[self convertDecimalToChar:num] withString:[self convertDecimalToChar:num+1]];

NSLog(@"CHAR:%@ and look for:%@ replace with:%@ results in %@",chars,[self convertDecimalToChar:num],[self convertDecimalToChar:num+1], replaced);

如果NSMutableString使用replaceCharactersInRange:withString:

[chat replaceCharactersInRange:[self convertDecimalToChar:num]withString:[self convertDecimalToChar:num+1];

replaceOccurrencesOfString:withString:options:range:如果您需要更多选项,例如不区分大小写的替换:

NSRange range = NSMakeRange(0, [char length]);
[char replaceOccurrencesOfString:[self convertDecimalToChar:num] withString:[self convertDecimalToChar:num+1] options:NSCaseInsensitiveSearch range:range];

如果您还想要替换以匹配给定字符串的大小写,则可能需要使用搜索选项NSLiteralSearch