How to check if a phrase/string contains words from a list in Kotlin

Asked

Viewed 24 times

0

I’m having trouble with the operator in, when I have only one operating i can easily verify if a certain word is contained in a list, for example:

fun main(){
    val cores = listOf(
            "branco",
            "azul",
            "verde"
    )
    val cor = "azul"

    if(cor in cores){
        println("Está contido!")
    }
    else{
        println("Não está contido!")
    }
}


But when I have several operand to check (as in a sentence for example) I have the problem where it checks only the first word of the phrase, in python I would solve this problem using the for to go through each word of the phrase, but in Kotlin this does not work, even if a word from the list is the first to appear phrase does not work.

code:

fun main(){
    val cores = listOf(
        "branco",
        "azul",
        "verde"
    )
    val frase = "Eu gosto da cor azul"

    for(palavra in frase){
        if(palavra.toString() in cores){
            println("Está contido!")
        }
        else{
            println("Não está contido!")
        }
    }
}

1 answer

0


What you’re doing makes no sense. What you have to do is use the method contains to check if a word exists in a string.

For example:

fun main() {
    val cores = listOf(
            "branco",
            "azul",
            "verde"
    )
    val frase = "Eu gosto da cor azul"
    
    for(cor in cores){
        if(frase.contains(cor)){
            println("A cor '${cor}' Está contido!")
        }
        else{
            println("A cor '${cor}' Não está contido!")
        }
    }
}

Just out of curiosity, doing for(palavra in frase) o for will pass through each character of the string frase instead of every word.

  • Thank you so much, it worked here, I did not know this method, very good!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.