0

I am creating a simple chat bot using swift 3 in Xcode 8, and have been looking for a way to search for a specific word in a string.

For example:

If the user inputs "I would like to have a cup of coffee please."

The program then checks the string for the word "coffee" then finding "coffee" in the string it then returns bool.

I know that you can do this in python:

phrase = "I would like to have a cup of coffee please."
if "coffee" in phrase 
    print('hi there')

How would you do this in swift 3?

Thanks

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Xi O
  • 21
  • 1
  • 4

1 Answers1

3

Swift 4...

Using contains(_:) (See String's ref in Swift 4):

let haystack = "I would like to have a cup of coffee please."
let needle = "like"
print(haystack.contains(needle))

Swift 3..<4

Using range(of:..) (See String's ref in Swift 3):

let haystack = "I would like to have a cup of coffee please."
let needle = "like"

if let exists = haystack.range(of: needle) {
    // Substring exists
}
nathan
  • 9,329
  • 4
  • 37
  • 51