Chetan Tuteja
12/27/2021, 7:19 AMin
check for that.
Is there any way to do the same check while ignoring case check?
I know I can do the any
check, anything besides that?
val abc = "abc"
val random = arrayOf("ABC", "egf")
val isThere = abc in random // Prints false
ephemient
12/27/2021, 7:30 AMrandom.any { abc.equals(it, ignoreCase = true) }
Chetan Tuteja
12/27/2021, 7:31 AMephemient
12/27/2021, 7:44 AMChetan Tuteja
12/27/2021, 7:47 AMfun String.isIgnoreCasePresentIn(input: Array<String>): Boolean {
return input.any { inp -> inp.equals(this, ignoreCase = true) }
}
ephemient
12/27/2021, 7:49 AMabc.lowercase() in random.map { it.lowercase() }
, abc.uppercase() in random.map { it.uppercase() }
, and even abc.uppercase().lowercase() in random.map { it.uppercase().lowercase() }
will not be quite right for some inputs in some locales (this is where a proper Unicode casefold would be useful), but for most inputs something like that will likely work. if you're doing many membership tests with the same collection, you will probably be better off doing that with a Set
ishwar verma
12/27/2021, 9:43 AMarchecraft
12/27/2021, 10:33 AMisThere = abc in random.ignoringCase()
. Would still require to use e.g. the any
check, but would look nicer on the use sideMrNiamh
12/27/2021, 10:36 AMChetan Tuteja
12/27/2021, 10:39 AMephemient
12/27/2021, 11:26 AMval caseFold = CaseMap.fold()
val randomCaseFolded = buildSet { random.mapTo(this) { caseFold.apply(it) } }
caseFold.apply(abc) in randomCaseFolded
but .lowercase()
or .uppercase()
works if only have ASCII inputs and .uppercase().lowercase()
should work for most other than Turkic languagesShawn
12/27/2021, 4:09 PMval caseInsensitiveSet = TreeSet(String.CASE_INSENSITIVE_ORDER)
.apply { addAll(setOf("ABC", "egf")) }
"abc" in caseInsensitiveSet // true
The caveats relating to locale-specific rules on case still apply, though java.text.Collator
has provisions for locale-aware logic. Also, yes, this particular solution is Java-specific, but I think the approach itself holds across platforms.ephemient
12/28/2021, 12:21 AMbuildSet()
), but it's probably the best option if you need other collationsArxing Lin
12/28/2021, 8:15 AMfun main() {
val abc = "abc"
val random = arrayOf("ABC", "egf")
println(abc in random) // return true
}
operator fun Array<String>.contains(element: String): Boolean = any {
it.equals(element, true)
}
Chetan Tuteja
12/28/2021, 8:37 AMArxing Lin
12/28/2021, 8:55 AMinfix
functions like that:
fun main() {
val abc = "abc"
val random = arrayOf("ABC", "egf")
println(abc ignoreCaseIn random) // return true
}
infix fun String.ignoreCaseIn(array: Array<String>): Boolean = array.any {
it.equals(this, true)
}
Chetan Tuteja
12/28/2021, 9:55 AM