Kotlin – Check if String Starts with Specified String Value

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

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

str1.startsWith(str2)

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

Example 1 – Check if String Starts with Specified String Value

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

Kotlin Program

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

Output

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

Example 2 – Negative Scenario

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

Kotlin Program

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

Since, we have taken string values in str1 and str2 such that str1 does not start with specified string value str2, the method returns false.

Output

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

Conclusion

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