区分大小写Kotlin/ignoreCase

sup*_*ron 6 case-insensitive kotlin

我试图忽略字符串的区分大小写.例如,用户可以放置"巴西"或"巴西",乐趣将触发.我该如何实现?我是Kotlin的新手.

fun questionFour() {
    val edittextCountry = findViewById<EditText>(R.id.editTextCountry)
    val answerEditText = edittextCountry.getText().toString()

    if (answerEditText == "Brazil") {
        correctAnswers++
    }

    if (answerEditText == "Brasil") {
        correctAnswers++
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

另一个人帮我写这样的.我现在关于这种方式的问题是"有更简洁的方式来写这个吗?"

fun questionFour() {
    val edittextCountry = findViewById<EditText>(R.id.editTextCountry)
    val answerEditText = edittextCountry.getText().toString()

    if (answerEditText.toLowerCase() == "Brazil".toLowerCase() || answerEditText.toLowerCase() == "Brasil".toLowerCase()) {
        correctAnswers++
    }
}
Run Code Online (Sandbox Code Playgroud)

回答

fun questionFour() {

        val edittextCountry = findViewById<EditText>(R.id.editTextCountry)
        val answerEditText = edittextCountry.getText().toString()

        if (answerEditText.equals("brasil", ignoreCase = true) || answerEditText.equals("brazil", ignoreCase = true)) {
            correctAnswers++
        }
    }
Run Code Online (Sandbox Code Playgroud)

Sha*_*cts 12

您可以equals直接调用该函数,这将允许您指定可选参数ignoreCase:

if (answerEditText.equals("brasil", ignoreCase = true)) {
    correctAnswers++
}
Run Code Online (Sandbox Code Playgroud)

  • 如果答案适合您,请务必接受答案(单击复选标记). (2认同)

Tod*_*odd 7

核心问题是==只调用 to equals(),这是区分大小写的。有几种方法可以解决这个问题:

1)小写输入并直接比较:

if (answerEditText.toLowerCase() == "brasil" ||
    answerEditText.toLowerCase() == "brazil") {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

这很容易理解和维护,但是如果您有多个答案,它就会变得笨拙。

2) 小写输入并测试集合中的值:

if (answerEditText.toLowerCase() in setOf("brasil", "brazil")) {
    // Do Something
}
Run Code Online (Sandbox Code Playgroud)

也许将集合定义为某个地方的常量(在伴随对象中?)以避免多次重新创建它。这很好而且很清楚,当你有很多答案时很有用。

3)忽略大小写并通过.equals()方法进行比较:

if (answerEditText.equals("Brazil", true) ||
    answerEditText.equals("Brasil", true)) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

与选项 1 类似,当您只有一堆答案需要处理时很有用。

4) 使用不区分大小写的正则表达式:

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

同样,创建answer一次正则表达式并将其存储在某处以避免重新创建。我觉得这是一个矫枉过正的解决方案。