How to replace a string in NSMutableString from another string

I have an NSMutableString that holds the word twice (e.g. / abc ...................... / abc).

Now I want to replace these two occurrences of / abc with / xyz. I want to replace only the first and last appearance with other cases.

 - (NSUInteger)replaceOccurrencesOfString:(NSString *)target
                               withString:(NSString *)replacement
                                  options:(NSStringCompareOptions)opts 
                                    range:(NSRange)searchRange

I find this NSMutableString instance method, but I cannot use it in my case. Anyone have any solution?

+3
source share
1 answer

You can first find two ranges and then replace them separately:

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"];
}
+5
source

Source: https://habr.com/ru/post/1764468/


All Articles