Eric Brotto Eric Brotto - 11 days ago 7
Objective-C Question

Replace only the first instance of a substring in an NSString

So if you have an NSString that goes:

@"My blue car is bigger than my blue shoes or my blue bicycle";


I would like a method that replaces only the first instance of blue with green, to produce:

@"My green car is bigger than my blue shoes or my blue bicycle";


How does one do this?

Answer

Assuming the following inputs:

NSString *myString = @"My blue car is bigger then my blue shoes or my blue bicycle";
NSString *original = @"blue";
NSString *replacement = @"green";

The algorithm is quite simple:

NSRange rOriginal = [myString rangeOfString: original];
if (NSNotFound != rOriginal.location) {
    myString = [myString
        stringByReplacingCharactersInRange: rOriginal
        withString:                         replacement];
}