How to replace the first occurrence of a substring in a string with Swift

1 Answer

0 votes
import Foundation

func replaceFirst(in input: String, target: String, replacement: String) -> String {
    if let range = input.range(of: target) {
        return input.replacingCharacters(in: range, with: replacement)
    }
    return input
}


let s = "aa bb cc dd ee cc"

let updatedString = replaceFirst(in: s, target: "cc", replacement: "YY")

print(updatedString)



/*
run:

aa bb YY dd ee cc

*/

 



answered Jul 21, 2025 by avibootz
...