不区分大小写地检查字符串是否存在于数组中

Check if a string exists in an array case insensitively

声明:

let listArray = ["kashif"]
let word = "kashif"

然后这个

contains(listArray, word) 

Returns true 但如果声明是:

let word = "Kashif"

那么它 returns false 因为比较是区分大小写的。

如何让这个比较不区分大小写?

你可以使用

word.lowercaseString 

将字符串全部转为小写字符

试试这个:

let loword = word.lowercaseString
let found = contains(listArray) { [=10=].lowercaseString == loword }

Xcode 8 • Swift 3 或更高版本

let list = ["kashif"]
let word = "Kashif"

if list.contains(where: {[=10=].caseInsensitiveCompare(word) == .orderedSame}) {
    print(true)  // true
}

或者:

if list.contains(where: {[=11=].compare(word, options: .caseInsensitive) == .orderedSame}) {
    print(true)  // true
}

如果您想知道元素在数组中的位置(它可能会找到多个与谓词匹配的元素):

let indices = list.indices.filter { list[[=12=]].caseInsensitiveCompare(word) == .orderedSame }
print(indices)  // [0]

您还可以使用 localizedStandardContains 方法,该方法不区分大小写和变音符号,并且也可以匹配子字符串:

func localizedStandardContains<T>(_ string: T) -> Bool where T : StringProtocol

Discussion This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.

let list = ["kashif"]
let word = "Káshif"

if list.contains(where: {[=14=].localizedStandardContains(word) }) {
    print(true)  // true
}

我的例子

func updateSearchResultsForSearchController(searchController: UISearchController) {
    guard let searchText = searchController.searchBar.text else { return }
    let countries = Countries.getAllCountries()
    filteredCountries = countries.filter() {
        return [=10=].name.containsString(searchText) || [=10=].name.lowercaseString.containsString(searchText)
    }
    self.tableView.reloadData()
}

要检查数组中是否存在字符串(不区分大小写),请使用

listArray.localizedCaseInsensitiveContainsString(word) 

其中 listArray 是数组的名称 word 是您搜索的文本

此代码适用于 Swift 2.2

SWIFT 3.0:

在字符串数组中查找不区分大小写的字符串很酷,但是如果没有索引,在某些情况下就不会很酷。

这是我的解决方案:

let stringArray = ["FOO", "bar"]()
if let index = stringArray.index(where: {[=10=].caseInsensitiveCompare("foo") == .orderedSame}) {
   print("STRING \(stringArray[index]) FOUND AT INDEX \(index)")
   //prints "STRING FOO FOUND AT INDEX 0"                                             
}

这比其他答案更好 b/c 你在数组中有对象的索引,所以你可以抓住对象并做任何你想做的事情:)

Swift 4

让所有内容(查询和结果)不区分大小写。

for item in listArray {
    if item.lowercased().contains(word.lowercased()) {
        searchResults.append(item)
    }
}

用于检查一个字符串是否存在于数组中选项(不区分大小写,anchored/search仅限于启动)

使用基金会 range(of:options:)

let list = ["kashif"]
let word = "Kashif"


if list.contains(where: {[=10=].range(of: word, options: [.caseInsensitive, .anchored]) != nil}) {
    print(true)  // true
}

if let index = list.index(where: {[=10=].range(of: word, options: [.caseInsensitive, .anchored]) != nil}) {
    print("Found at index \(index)")  // true
}

扩展@Govind Kumawat 的回答

searchStringword 的简单比较是:

word.range(of: searchString, options: .caseInsensitive) != nil

作为函数:

func containsCaseInsensitive(searchString: String, in string: String) -> Bool {
    return string.range(of: searchString, options: .caseInsensitive) != nil
}

func containsCaseInsensitive(searchString: String, in array: [String]) -> Bool {
    return array.contains {[=11=].range(of: searchString, options: .caseInsensitive) != nil}
}

func caseInsensitiveMatches(searchString: String, in array: [String]) -> [String] {
    return array.compactMap { string in
        return string.range(of: searchString, options: .caseInsensitive) != nil
            ? string
            : nil
    }
}

swift 5、swift 4.2、使用下面的代码

let list = ["kAshif"]
let word = "Kashif"

if list.contains(where: { [=10=].caseInsensitiveCompare(word) == .orderedSame }) {
    print("contains is true")
}

您可以添加扩展名:

Swift 5

extension Array where Element == String {
    func containsIgnoringCase(_ element: Element) -> Bool {
        contains { [=10=].caseInsensitiveCompare(element) == .orderedSame }
    }
}

并像这样使用它:

["tEst"].containsIgnoringCase("TeSt") // true

如果有人想从模型 class 中搜索值,请说

struct Country {
   var name: String
}

一个案例做如下不区分大小写的检查 -

let filteredList = countries.filter({ [=11=].name.range(of: "searchText", options: .caseInsensitive) != nil })