web-dev-qa-db-ja.com

大文字と小文字の区別Kotlin / ignoreCase

文字列の大文字と小文字の区別を無視しようとしています。たとえば、ユーザーは「ブラジル」または「ブラジル」を置くことができ、楽しみがトリガーされます。これを実装するにはどうすればよいですか? 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++
        }
    }
6
superheron

equals 関数を直接呼び出すことができます。これにより、オプションのパラメーターignoreCaseを指定できます。

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

主要な問題は、_==_がequals()を呼び出すだけであり、大文字と小文字が区別されることです。これを解決する方法はいくつかあります。

1)入力を小文字にして直接比較します。

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

これは理解と維持が簡単ですが、答えが2つ以上あると、扱いにくくなります。

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正規表現を一度作成し、再作成を避けるためにどこかに保存します。これはやり過ぎの解決策だと思います。

4
Todd

拡張関数を作成して使用しているため、2番目のパラメーターを指定する必要がありません。

fun String.equalsIgnoreCase(other: String?): Boolean {
    if (other == null) {
        return false
    }

    return this.equals(other, true)
}

println("California".equalsIgnoreCase("CALIFORNIA"))
0
realfire