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.

2 Answers 2

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 );
Sign up to request clarification or add additional context in comments.

1 Comment

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!
3

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

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

2 Comments

Very helpful but the other answerer got here first so I had to give him credit--still, thanks so much.
No Problem, just wanted to show how easy it is to do this task with Objective-C's inbuilt methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.