Search code examples
swiftswift3swift4

Swift find the end index of a word within a string


I have a string. I have a word inside that string

I want to basically get rid of everything in the string and the word. But everything after the word in the string I want to keep. This word and string can be dynamic.

Here is what I got so far and I am finding it hard to find online resources to solve this.

Error:

Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')

Here is my code

            var bigString = "This is a big string containing the pattern"
            let pattern = "containing" //random word that is inside big string
            let indexEndOfPattern = bigString.lastIndex(of: pattern) // Error here
            let newText = bigString[indexEndOfPattern...]
            bigString = newText // bigString should now be " the pattern"

Solution

  • Think in ranges and bounds, lastIndex(of expects a single Character

    var bigString = "This is a big string containing the pattern"
    let pattern = "containing" //random word that is inside big string
    if let rangeOfPattern = bigString.range(of: pattern) {
        let newText = String(bigString[rangeOfPattern.upperBound...])
        bigString = newText // bigString should now be " the pattern"
    }