在字符串swift 3.0中搜索数组元素

时间:2017-09-11 15:08:55

标签: swift3

我想在字符串中搜索字符串数组的元素。像这样:

let array:[String] = ["dee", "kamal"]
let str:String = "Hello all how are you, I m here for deepak."

所以,我想要

str.contain("dee") == true

任何可能的字符串搜索?

3 个答案:

答案 0 :(得分:2)

您可以通过编写正则表达式模式"(item1|item2|item3)"

在一行中完成
let array = ["dee", "kamal"]
let str = "Hello all how are you, I m here for deepak."

let success = str.range(of: "(" + array.joined(separator: "|") + ")", options: .regularExpression) != nil

答案 1 :(得分:0)

您应该迭代数组,并为每个元素调用str.contains

for word in array {
    if str.contains(word) {
        print("\(word) is part of the string")
    } else {
        print("Word not found")
    }
}

答案 2 :(得分:0)

你可以这样做:

array.forEach { (item) in
   var isContains:Bool = str.contains(item)
   print(isContains)
}