Kotlin – Check if String Starts with Specified Character

To check if String starts with specified character in Kotlin, use String.startsWith() method.

Given a string str1, and if we would like to check if this string starts with the character ch, call startsWith() method on string str1 and pass the character ch as argument to the method as shown below.

str1.startsWith(ch)

startsWith() method returns a boolean value of true if the string str1 starts with the character ch, or false if not.

Example 1 – Check if String Starts with Specified Character

In this example, we will take a string in str1, and check if it starts with character 'a' using String.startsWith() method.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcdefg"
    val ch = 'a'
    val result = str1.startsWith(ch)
    println("startsWith() returns  : " + result)
    if( result ) {
        println("String starts with specified character.")
    } else {
        println("String does not start with specified character.")
    }
}

Output

startsWith() returns  : true
String starts with specified character.

Example 2 – Negative Scenario

In this example, we will take a string in str1, and check if it starts with character 'd' using String.startsWith() method.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcdefg"
    val ch = 'd'
    val result = str1.startsWith(ch)
    println("startsWith() returns  : " + result)
    if( result ) {
        println("String starts with specified character.")
    } else {
        println("String does not start with specified character.")
    }
}

Since, we have taken a string in str1 such that it does not start with specified character, the method returns false.

Output

startsWith() returns  : false
String does not start with specified character.

Conclusion

In this Kotlin Tutorial, we learned how to check if the given string starts with specified character, using String.startsWith() method, with the help of Kotlin example programs.