Posts

Showing posts with the label Contains

Check If A String Exists In An Array Case Insensitively

Answer : 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: 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 s...

Better Way To Detect If A String Contains Multiple Words

Answer : I'd create a regular expression from the words: Pattern pattern = Pattern.compile("(?=.*adsf)(?=.*qwer)"); if (pattern.matcher(input).find()) { execute(); } For more details, see this answer: https://stackoverflow.com/a/470602/660143 Editors note: Despite being heavily upvoted and accepted, this does not function the same as the code in the question. execute is called on the first match, like a logical OR. You could use an array: String[] matches = new String[] {"adsf", "qwer"}; bool found = false; for (String s : matches) { if (input.contains(s)) { execute(); break; } } This is efficient as the one posted by you but more maintainable. Looking for a more efficient solution sounds like a micro optimization that should be ignored until proven to be effectively a bottleneck of your code, in any case with a huge string set the solution could be a trie. In Java 8 you could do public static boolean containsWords(S...