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

1 Answer

0 votes
import Foundation

func replaceLastOccurrence(s: String, oldsub: String, newsub: String) -> String? {
    guard let range = s.range(of: oldsub, options: .backwards) else {
        return s
    }
    return s.replacingCharacters(in: range, with: newsub)
}

let s = "Swift programming is a powerful and intuitive programming language"
        
let oldsub = "programming"
let newsub = "ABC"
        
if let result = replaceLastOccurrence(s: s, oldsub: oldsub, newsub: newsub) {
    print(result)
}



/*
run:

Swift programming is a powerful and intuitive ABC language

*/

 



answered Dec 28, 2024 by avibootz
...