如何在Objective C中用另一个替换一个子字符串?

问题描述:

我想用 Objective C 中的另一个子字符串替换 NSString 子字符串.

I want to replace an NSString substring with another substring in Objective C.

我知道如何定位要替换的子字符串:

I know how to locate the substring I want to replace:

        NSRange range = [string rangeOfString:substringIWantToReplace];
        NSString *substring = [string substringFromIndex:NSMaxRange(range)];

但是当谈到实际删除/替换它时,我有点困惑.我是否遵循 用另一个子字符串 C++ 替换子字符串 中的 C++ 方法?或者如何替换c中的子串?中的C方法?Objective-C: Substring and replace 有一个相关的问题,但有问题的字符串是一个网址,所以我认为我不能使用答案.

But when it comes to actually removing/replacing it, I'm a little confused. Do I follow the C++ method at Replace substring with another substring C++? Or the C method at how to replace substring in c?? There's a related question at Objective-C: Substring and replace, but the string in question is a URL, so I don't think I can use the answers.

我想你的答案就在这里 替换出现的 NSString - iPhone:[response stringByReplacingOccurrencesOfString:@"aaa" withString:@"bbb"]; defenet 也适用于任何字符串和 URL.

I think your answer is here Replace occurrences of NSString - iPhone: [response stringByReplacingOccurrencesOfString:@"aaa" withString:@"bbb"]; defenetly works on any string and URL also.

如果您担心 url 的百分比表示法并且您想确保它会被正确替换,您可以先解码字符串,替换,然后编码:

If your concern about percent-notation of url and you want to be sure it will be replaced properly, you can firstly decode string, replace, and then encode:

// decode
NSString *path = [[@"path+with+spaces"
    stringByReplacingOccurrencesOfString:@"+" withString:@" "]
    stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// replace
path = [path stringByReplacingOccurrencesOfString:@"aaa" withString:@"bbb"]
// encode
path = CFURLCreateStringByAddingPercentEscapes(
                                               NULL,
                                               (CFStringRef)path,
                                               NULL,
                                               (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                               kCFStringEncodingUTF8 );