Reputation: 831
I have a NSMutableString that contains a word twice.(e.g. /abc ...................... /abc).
Now I want to replace these two occurrences of /abc with /xyz. I want to replace only first and last occurence no other occurences.
- (NSUInteger)replaceOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement
options:(NSStringCompareOptions)opts
range:(NSRange)searchRange
I find this instance method of NSMutableString but I am not able to use it in my case. Anyone have any solution??
Upvotes: 3
Views: 5530
Reputation: 98984
You can first find the two ranges and then replace them seperately:
NSMutableString *s = [NSMutableString stringWithString:@"/abc asdfpjklwe /abc"];
NSRange a = [s rangeOfString:@"/abc"];
NSRange b = [s rangeOfString:@"/abc" options:NSBackwardsSearch];
if ((a.location == NSNotFound) || (b.location == NSNotFound)) {
// at least one of the substrings not present
} else {
[s replaceCharactersInRange:a withString:@"/xyz"];
[s replaceCharactersInRange:b withString:@"/xyz"];
}
Upvotes: 5