Kotlin – Check if String contains specific Character

Check if String contains specified Character in Kotlin

To check if given string contains specified character in Kotlin, you can use String.contains() function.

Call contains() function on the given String object str, and pass the character in ch as argument to the function.

str.contains(ch)

If the string str contains the character ch, 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 @ symbol

Consider that we have a requirement that we need to check if given string contains the character @.

In the following program, we take a string value in str, and validate if this string contains the specified character.

Kotlin Program

fun main() {
    val str = "apple@123"
    val ch = '@'
    if ( str.contains(ch) ) {
        println("String contains $ch.")
    } else {
        println("String does not contain $ch.")
    }
}

Output

String contains @.

Negative Scenario

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

Kotlin Program

fun main() {
    val str = "apple123"
    val ch = '@'
    if ( str.contains(ch) ) {
        println("String contains $ch.")
    } else {
        println("String does not contain $ch.")
    }
}

Output

String does not contain @.