我有一个包含许多字符串的数组。我已经使用contains()
(请参阅下文)检查数组中是否存在某个字符串,但是我想检查字符串中是否有一部分字符串?
itemsArray = ["Google, Goodbye, Go, Hello"]
searchToSearch = "go"
if contains(itemsArray, stringToSearch) {
NSLog("Term Exists")
}
else {
NSLog("Can't find term")
}
上面的代码只是检查数组中是否存在一个值,但是我想找到 "Google, Google and Go"
尝试这样。
let itemsArray = ["Google", "Goodbye", "Go", "Hello"]
let searchToSearch = "go"
let filteredStrings = itemsArray.filter({(item: String) -> Bool in
var stringMatch = item.lowercaseString.rangeOfString(searchToSearch.lowercaseString)
return stringMatch != nil ? true : false
})
filteredStrings
将包含具有匹配子字符串的字符串列表。
在Swift中,Array
struct提供了filter方法,它将基于过滤文本条件来过滤提供的数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句