Replace only the first instance of a substring in an NSString

7 Solutions Collect From Internet About “Replace only the first instance of a substring in an NSString”

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];
}

In Swift is useful extends String in this way:

public extension String {

    func stringByReplacingFirstOccurrenceOfString(target: String, withString replaceString: String) -> String {
        if let range = self.rangeOfString(target) {
            return self.stringByReplacingCharactersInRange(range, withString: replaceString)
        }
        return self
    }

}

In this way you can call wherever:

let s = "The red red cat".stringByReplacingFirstOccurrenceOfString("red", withString: "fat")
print(s) // "The fat red cat"

SWIFT 3 UPDATE:

extension String 
{
    func stringByReplacingFirstOccurrenceOfString(
            target: String, withString replaceString: String) -> String
    {
        if let range = self.range(of: target) {
            return self.replacingCharacters(in: range, with: replaceString)
        }
        return self
    } 
}
  NSString *initialString = @"My blue car is bigger then my blue shoes or my blue bicycle";
  NSRange range = [initialString rangeOfString:@"blue"];
  NSString *replacedString = [initialString stringByReplacingCharactersInRange:range withString:@"green"];
  NSLog(@"replacedString: %@", replacedString);

Swift 4 version:

func replacingFirstOccurrence(of string: String, with replacement: String) -> String {
    guard let range = self.range(of: string) else { return self }
    return replacingCharacters(in: range, with: replacement)
}

First locate the substring, and then make the replacement. Example :

NSString *aString = @"foo bar foo";
NSRange firstFooRange = [aString rangeOfString:@"foo"];
NSString *anotherString = [aString stringByReplacingOccurrencesOfString:@"foo"
                                                             withString:@"bar"
                                                                options:0
                                                                  range:firstFooRange];

NSString documentation.

-(NSString*) replaceFirstOccuarnceFromString: (NSString*)input withOriginal:(NSString*) original AndReplacment:(NSString*)replacement
{
    NSRange rOriginal = [input rangeOfString: original];
    if (NSNotFound != rOriginal.location) {
        input = [input
                    stringByReplacingCharactersInRange: rOriginal
                    withString:                         replacement];
    }
    return input;
}