In this tutorial, you shall learn how to check if given string starts with a specific prefix string in Kotlin, using String.startsWith() function, with examples.

Kotlin – Check if string starts with specific prefix string

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.

Examples

ADVERTISEMENT

1. Check if string starts with prefix string “abc”

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.

2. Check if string starts with “mno”

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.