2

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.

Community
  • 1
  • 1
Joel Derfner
  • 2,207
  • 6
  • 33
  • 45

2 Answers2

7

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 );
Community
  • 1
  • 1
Daniil
  • 5,760
  • 5
  • 18
  • 29
  • Thank you! I meant actually that the string in the other question was a URL, where my string isn't. The answers in that question seem based on the fact that it's a URL. But anyway your answer gave me what I needed--thank you! – Joel Derfner Jan 04 '13 at 02:14
3

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

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