Find and replace substring in Swift 4

Here’s how to find a substring in Swift 4.

import Foundation

// find substring
var s = "bird mouse fish"
let strToFind = "mouse"
var ns = s as NSString
// case sensitive find
if (ns.contains(strToFind)) {
    print("substring found")
}

// case insensitive find
let range = ns.range(of: strToFind, options: .caseInsensitive)
if range.location != NSNotFound {
    // replace
    s = ns.replacingCharacters(in: range, with: "cat")
    print(s)  // it prints "bird cat fish"
}

We simply convert our String to an NSString so we can use the contains function or the range(of: options:) function.
To replace the substring, we again use a NSString method: replacing Characters(in: with:).

 

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *