检查数组是否包含

检查数组是否包含

本文介绍了检查数组是否包含 Swift 中字符串的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个字符串的数组.我已经使用 contains()(见下文)来检查数组中是否存在某个字符串,但是我想检查字符串的一部分是否在数组中?

I have an array containing a number of strings. I have used contains() (see below) to check if a certain string exists in the array however I would like to check if part of a string is in the array?

itemsArray = ["Google, Goodbye, Go, Hello"]

searchToSearch = "go"

if contains(itemsArray, stringToSearch) {
    NSLog("Term Exists")
}
else {
    NSLog("Can't find term")
}

上面的代码只是检查数组中是否存在一个完整的值,但是我想找到 "Google, Google and Go"

The above code simply checks if a value is present within the array in its entirety however I would like to find "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 将包含具有匹配子字符串的字符串列表.

filteredStrings will contain the list of strings having matched sub strings.

在 Swift Array struct 中提供了 filter 方法,该方法将根据过滤文本条件过滤提供的数组.

In Swift Array struct provides filter method, which will filter a provided array based on filtering text criteria.

这篇关于检查数组是否包含 Swift 中字符串的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:47