In this tutorial, you shall learn how to check if a given string contains a specific character in Kotlin, using String.contains() function, with the help of examples.

Kotlin – Check if string contains specific character

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

Call the contains() function on the given string, and pass the character to search in the string as argument. The function returns boolean value of true if the string contains specified character, else it returns false.

Examples

1. Check if “helloworld” contains the character ‘r’

In the following program, we take a string in str, and check if this string contains the character 'r' using String.contains() function.

Main.kt

</>
Copy
fun main() {
    val str = "helloworld"
    val ch = 'r'
    if (str.contains(ch)) {
        println("$str contains $ch.")
    } else {
        println("$str does not contain $ch.")
    }
}

Output

helloworld contains r.

2. String does not contain specific character [Negative Scenario]

In the following program, we take a string "helloworld" in str, and then check if this string contains the character 'm'. Since the string does not contain the specified character, the function returns false and else block will be executed.

Main.kt

</>
Copy
fun main() {
    val str = "helloworld"
    val ch = 'm'
    if (str.contains(ch)) {
        println("$str contains $ch.")
    } else {
        println("$str does not contain $ch.")
    }
}

Output

helloworld does not contain m.

Related Tutorials

Conclusion

In this Kotlin Tutorial, we learned how to check if given string contains specific character using String.contains() function.