In this tutorial, you shall learn how to check if given string starts with a specified character in Kotlin, using String.startsWith() function, with examples.
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.
Examples
1. Check if string starts with the character ‘a’
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.
2. Check if string starts with ‘d’
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.