Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace one substring with another in Objective C?

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)];

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.

like image 516
Joel Derfner Avatar asked Dec 04 '25 17:12

Joel Derfner


1 Answers

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

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 );
like image 126
Daniil Avatar answered Dec 06 '25 07:12

Daniil