Check if a string exists in an array case insensit

2019-01-25 02:39发布

Declaration:

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

then this

contains(listArray, word) 

Returns true but if declaration is:

let word = "Kashif"

then it returns false because comparison is case sensitive.

How to make this comparison case insensitive?

8条回答
Ridiculous、
2楼-- · 2019-01-25 03:13

you can use

word.lowercaseString 

to convert the string to all lowercase characters

查看更多
时光不老,我们不散
3楼-- · 2019-01-25 03:16

For checking if a string exists in a array with more Options(caseInsensitive, anchored/search is limited to start)

using Foundation range(of:options:)

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


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

if let index = list.index(where: {$0.range(of: word, options: [.caseInsensitive, .anchored]) != nil}) {
    print("Found at index \(index)")  // true
}
查看更多
可以哭但决不认输i
4楼-- · 2019-01-25 03:20

SWIFT 3.0:

Finding a case insensitive string in a string array is cool and all, but if you don't have an index it can not be cool for certain situations.

Here is my solution:

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

This is better than the other answers b/c you have index of the object in the array, so you can grab the object and do whatever you please :)

查看更多
够拽才男人
5楼-- · 2019-01-25 03:25
let list = ["kashif"]
let word = "Kashif"

if contains(list, {$0.caseInsensitiveCompare(word) == NSComparisonResult.OrderedSame}) {
    println(true)  // true
}

Xcode 7.3.1 • Swift 2.2.1

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

Xcode 8 • Swift 3 or later

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

alternatively:

if list.contains(where: {$0.compare(word, options: .caseInsensitive) == .orderedSame}) {
    print(true)  // true
}
查看更多
ら.Afraid
6楼-- · 2019-01-25 03:26

For checking if a string exists in a array (case insensitively), please use

listArray.localizedCaseInsensitiveContainsString(word) 

where listArray is the name of array and word is your searched text

This code works in Swift 2.2

查看更多
虎瘦雄心在
7楼-- · 2019-01-25 03:29

Try this:

let loword = word.lowercaseString
let found = contains(listArray) { $0.lowercaseString == loword }
查看更多
登录 后发表回答