3

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

James Van Boxtel
  • 2,365
  • 4
  • 22
  • 33
Greshi Gupta
  • 831
  • 2
  • 10
  • 16
  • Is this for a URL? If so, there are a bunch of methods you can use in NSURL ("URLByDeletingLastPathComponent" for example: http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/URLByDeletingLastPathComponent) – Jamie Chapman Sep 13 '10 at 09:58
  • No,its not NSURL its just a NSMutableString. – Greshi Gupta Sep 13 '10 at 10:02

1 Answers1

5

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
  • 97,545
  • 26
  • 194
  • 236