Replace only the first instance of a substring in an NSString
A more Swift'y version of the implementations posted here. This one matches the syntax replacingOccurrences(of:with:)
in Swift 5.1
extension String {
func replacingFirstOccurrence(of target: String, with replacement: String) -> String {
guard let range = self.range(of: target) else { return self }
return self.replacingCharacters(in: range, with: replacement)
}
}
An example of usage:
let string = "I like bacon, please give me some more bacon!"
let newString = string.replacingFirstOccurrence(of: "bacon", with: "meat")
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];
}
SWIFT 3 and 4 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
}
}