Case Sensitivity Kotlin / ignoreCase

五迷三道 提交于 2019-12-04 05:22:16

You can call the equals function directly, which will allow you to specify the optional parameter ignoreCase:

if (answerEditText.equals("brasil", ignoreCase = true)) {
    correctAnswers++
}

The core problem is that == just calls through to equals(), which is case sensitive. There are a few ways to solve this:

1) Lowercase the input and direct compare:

if (answerEditText.toLowerCase() == "brasil" ||
    answerEditText.toLowerCase() == "brazil") {
    // Do something
}

This is easy to understand and maintain, but if you have more than a couple of answers, it gets unwieldy.

2) Lowercase the input and test for values in a set:

if (answerEditText.toLowerCase() in setOf("brasil", "brazil")) {
    // Do Something
}

Perhaps define the set as a constant somewhere (in a companion object?) to avoid recreating it a few times. This is nice and clear, useful when you have a lot of answers.

3) Ignore the case and compare via .equals() method:

if (answerEditText.equals("Brazil", true) ||
    answerEditText.equals("Brasil", true)) {
    // Do something
}

Similar to option 1, useful when you only have a coupe of answers to deal with.

4) Use a case insensitive regular expression:

val answer = "^Bra(s|z)il$".toRegex(RegexOption.IGNORE_CASE)
if (answer.matches(answerEditText)) {
    // Do something
}

Again, create the answer regex once and store it somewhere to avoid recreating. I feel this is an overkill solution.

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