1

Is it possible to change text within a specific part of an NSString? For example, I want to use stringByReplacingOccurrencesOfString, but only within a certain part of a string. In this example, I only want to replace #'s after #q=, and before &lang=en-us. Like this:

Initial string: https://google.com/search#q=hello#&lang=en-us

What it should be replaced with: https://google.com/search#q=hello%23&lang=en-us

What using stringByReplacingOccurrencesOfString returns if I tell it to replace #'s with %23: https://google.com/search%23q=hello%23&lang=en-us

Thanks for your help!

1
  • This is Q&A communitiy that works that provides free answer. You could pay back to the community by selecting correct answer that solves your problem and upvoting answer that guided in the right direction. This also improves your chances of getting answer Commented Sep 26, 2016 at 3:07

2 Answers 2

3

The direct answer to your question is yes, you can use stringByReplacingOccurrencesOfString:withString:options:range:; the range parameter specifies the part of the string within which replacements should be done.

There are other searching methods provide by NSString which may help you determine a suitable value for range.

Having said the above your approach is probably rather "fragile" - prone to break easily as input data changes - and maybe you should consider the string as what it is, a URL, and either construct it with appropriate escaping in the first place; or parse it into its parts, add the escaping, and then reassemble. There are methods on NSURL and NSString which help you do that.

HTH

Sign up to request clarification or add additional context in comments.

Comments

0

Seems like you want to URL encode existing string

NSString *input = @"https://google.com/search#q=hello%23&lang=en-us";
NSURL *url = @"https://google.com/search#q=hello%23&lang=en-us";
NSString *params = [url parameterString];
NSString *enc = [params stringByAddingPercentEscapesUsingEncoding:
 NSUTF8StringEncoding];
//append URLs host+path with enc

No error checking is done in above code, it only gives idea

1 Comment

Thanks for your response! The problem with this solution is that using this outputs the string with the hashtags and percent signs changed to the correct UTF8 encoding, but it does it for the entire string, not just within the #q= part.

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.