Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string exists in an array case insensitively

Tags:

contains

swift

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?

like image 775
Kashif Avatar asked Jul 09 '15 22:07

Kashif


People also ask

How do you check if a string exists in an array?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

Does string include case sensitive?

Both String#includes() and String#indexOf() are case sensitive. Neither function supports regular expressions. To do case insensitive search, you can use regular expressions and the String#match() function, or you can convert both the string and substring to lower case using the String#toLowerCase() function.

How do you check if an element already exists in an array?

The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.

How do I make something not case sensitive?

includes() method case insensitive, convert both of the strings in the comparison to lowercase, e.g. str. toLowerCase(). includes(substr. toLowerCase()) .


1 Answers

Xcode 8 • Swift 3 or later

let list = ["kashif"] let word = "Kashif"  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 } 

if you would like to know the position(s) of the element in the array (it might find more than one element that matches the predicate):

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

You can also use localizedStandardContains method which is case and diacritic insensitive and would match a substring as well:

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 } 
like image 89
Leo Dabus Avatar answered Oct 05 '22 23:10

Leo Dabus