我正在使用Xcode 8中的swift 3创建一个简单的聊天机器人,并且一直在寻找一种在字符串中搜索特定单词的方法。
例如:
如果用户输入“我想要一杯咖啡。”
然后程序检查字符串中的单词“coffee”,然后在字符串中找到“coffee”,然后返回bool。
我知道您可以在python中执行此操作:
phrase = "I would like to have a cup of coffee please."
if "coffee" in phrase
print('hi there')
在Swift 3里你会怎么做?
谢谢
迅速4...
使用包含(_:)
(参见Swift 4中String的参考文件):
let haystack = "I would like to have a cup of coffee please."
let needle = "like"
print(haystack.contains(needle))
迅速3...
使用范围(of:…)代码>(参见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
}