Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case insensitive matching search in string array swift 3

Tags:

ios

swift

swift3

In Swift 3, I want to create an array of matching string (case insensitive) from string array:-

I am using this code, but it is case sensitive,

let filteredArray = self.arrCountry.filter { $0.contains("india") }

how can I do this.. suppose I have a master string array called arrCountry, I want to create other array of all the string who has "india"(case insensitive) in it.

Can anyone help me out.

like image 293
Mayank Jain Avatar asked Oct 03 '16 12:10

Mayank Jain


4 Answers

You can try with localizedCaseInsensitiveContains

let filteredArray = self.arrCountry.filter { $0.localizedCaseInsensitiveContains("india") }
like image 89
Duyen-Hoa Avatar answered Nov 15 '22 00:11

Duyen-Hoa


localizedCaseInsensitiveContains
Returns a Boolean value indicating whether the given string is non-empty and contained within this string by case-insensitive, non-literal search, taking into account the current locale. Locale-independent case-insensitive operation, and other needs, can be achieved by calling range(of:options:range:locale:).

Equivalent to: range(of: other, options: .caseInsensitiveSearch, locale: Locale.current) != nil

It's better to use

.filter { $0.range(of: "india", options: .caseInsensitive) != nil }
like image 30
Nik Kov Avatar answered Nov 14 '22 22:11

Nik Kov


The easiest way might be to lowercase your strings and compare:

Swift 3 and above

let filteredArray = self.arrCountry.filter { $0.lowercased() == "india" }
like image 4
Jonathan Cabrera Avatar answered Nov 15 '22 00:11

Jonathan Cabrera


Answer 2020:

Even I put Chinese or Arabic, below test codes still returns TRUE

let text = "total sdfs"
let text1 = "Total 张"
let text2 = "TOTAL لطيف"
let text3 = "total :"
let text4 = "ToTaL : "



text.lowercased().contains("total")
text1.lowercased().contains("张")
text2.lowercased().contains("لطيف")
text3.lowercased().contains("total")
text4.lowercased().contains("total")


text.localizedCaseInsensitiveContains("total")
text1.localizedCaseInsensitiveContains("张")
text2.localizedCaseInsensitiveContains("لطيف")
text3.localizedCaseInsensitiveContains("total")
text4.localizedCaseInsensitiveContains("total")
like image 2
Sky Avatar answered Nov 14 '22 22:11

Sky