Joel Derfner
Joel Derfner

Reputation: 2207

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.

Upvotes: 2

Views: 3281

Answers (2)

Daniil
Daniil

Reputation: 5790

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

Upvotes: 7

user990230
user990230

Reputation: 307

This is how I check for a substring and replace/remove substrings from NSString:

if([titleName rangeOfString:@"""].location != NSNotFound) {
     titleName = [titleName stringByReplacingOccurrencesOfString:@""" withString:@"\""];
}

Upvotes: 3

Related Questions