1

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"
Peter
  • 68
  • 9
  • You say "error". That's very informative. Look at your screen and post the exact error message. And your approach doesn't work. You want to find the _range_ of the word "containing", and then delete everything up to the end index of that range. – gnasher729 Mar 08 '20 at 12:37
  • I posted the error first at the very top of my post. The "Error" within the code is referencing that this is where the above error shows. Is there not a String sub-function like substring, like in other languages? – Peter Mar 08 '20 at 12:49

1 Answers1

1

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"
}
vadian
  • 274,689
  • 30
  • 353
  • 361