tags:

views:

64

answers:

1

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??

A: 

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"];
}
Georg Fritzsche
It gives exception - "range out of bound". When I check the value of a and b it gives some garbage value(22666222).
Greshi Gupta
@Greshi: Remember to check for `NSNotFound`.
Georg Fritzsche