【问题标题】:Case Sensitivity Kotlin / ignoreCase大小写敏感性 Kotlin / ignoreCase
【发布时间】:2018-03-18 15:30:22
【问题描述】:

我试图忽略字符串的大小写敏感性。例如,用户可以输入“巴西”或“巴西”,乐趣就会触发。我该如何实施?我是 Kotlin 的新手。

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

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

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

编辑

另一个人帮我写成这样。我现在关于这种方式的问题是“有没有更干净的方式来写这个?”

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

    if (answerEditText.toLowerCase() == "Brazil".toLowerCase() || answerEditText.toLowerCase() == "Brasil".toLowerCase()) {
        correctAnswers++
    }
}

回答

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++
        }
    }

【问题讨论】:

  • 可能类似于:answerEditText.toLowerCase() in listOf("brazil", "brasil")
  • 如果你写val answerEditText = edittextCountry.text.toString().toLowerCase(),你也可以在if中避免toLowerCase

标签: kotlin case-insensitive


【解决方案1】:

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

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

【讨论】:

  • 效果很好!谢谢!
【解决方案2】:

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

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

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

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

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

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

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

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

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

类似于选项 1,当您只有几个答案要处理时很有用。

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

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

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

【讨论】:

    【解决方案3】:

    我们创建了扩展函数并使用它,因此我们可以避免指定第二个参数。

    fun String.equalsIgnoreCase(other: String?): Boolean {
        if (other == null) {
            return false
        }
    
        return this.equals(other, true)
    }
    
    println("California".equalsIgnoreCase("CALIFORNIA"))
    

    【讨论】:

    • 不需要 if (other == null) 检查。 equals() 函数,将可空值作为参数
    猜你喜欢
    • 2013-07-23
    • 1970-01-01
    • 2012-09-02
    • 2017-02-21
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多