Kotlin – Check if String contains given search string

Check if String contains specified Search String in Kotlin

To check if given string contains specified search string as a substring in Kotlin, you can use String.contains() function.

Call contains() function on the given String object str, and pass the search string searchString as argument to the function.

str.contains(searchString)

If the string str contains the search string searchString, then the contains() function returns true, else it returns false. We can use this as a condition in if-else statement.

Examples

Validate if string contains “red”

Consider that we have a requirement that we need to check if given encrypted message contains the word "red".

In the following program, we take the message as a string value in str, search string in searchString, and validate if the string str contains the specified search string.

Kotlin Program

fun main() {
    val str = "code red. i repeat code red."
    val searchString = "red"
    if ( str.contains(searchString) ) {
        println("The message contains $searchString")
    } else {
        println("The message does not contain $searchString")
    }
}

Output

The message contains red

Negative Scenario

In this example, we take a string in str such that it does not contain the specified search string.

Kotlin Program

fun main() {
    val str = "all ok. searching the parameter."
    val searchString = "red"
    if ( str.contains(searchString) ) {
        println("The message contains $searchString")
    } else {
        println("The message does not contain $searchString")
    }
}

Output

The message does not contain red