gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:04:40 56 4
gpt4 key购买 nike

声明:

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

然后这个

contains(listArray, word) 

返回 true 但如果声明是:

let word = "Kashif"

然后它返回 false,因为比较区分大小写。

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

最佳答案

Xcode 8 • Swift 3 或更高版本

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

if list.contains(where: {$0.caseInsensitiveCompare(word) == .orderedSame}) {
print(true) // true
}

或者:

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

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

let indices = list.indices.filter { list[$0].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: {$0.localizedStandardContains(word) }) {
print(true) // true
}

关于swift - 不区分大小写地检查字符串是否存在于数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31329568/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com