【问题标题】:Swift Searching for key words in a string [duplicate]快速搜索字符串中的关键词[重复]
【发布时间】:2018-02-03 02:23:23
【问题描述】:

我正在使用 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 中做到这一点?

谢谢

【问题讨论】:

    标签: swift


    【解决方案1】:

    斯威夫特 4...

    使用contains(_:)(参见Swift 4 中的String's ref):

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

    斯威夫特 3..

    使用range(of:..)(参见Swift 3 中的String's ref):

    let haystack = "I would like to have a cup of coffee please."
    let needle = "like"
    
    if let exists = haystack.range(of: needle) {
        // Substring exists
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-20
      • 2013-01-06
      • 2011-03-01
      • 1970-01-01
      • 2018-10-24
      • 2012-01-22
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多