case insensitive matching search in string array swift 3

有些话、适合烂在心里 提交于 2020-01-06 14:25:31

问题


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.


回答1:


You can try with localizedCaseInsensitiveContains

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



回答2:


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 }



回答3:


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

Swift 3 and above

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


来源:https://stackoverflow.com/questions/55590016/search-bar-is-happening-when-enter-the-exact-case-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!