【发布时间】: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。