In this tutorial, you shall learn how to check if given string ends with a specific suffix string in Kotlin, using String.endsWith() function, with examples.
Kotlin – Check if string ends with a specific suffix
To check if String ends with specified string value in Kotlin, use String.endsWith() method.
Given a string str1
, and if we would like to check if this string ends with the string str2
, call endsWith() method on string str1
and pass the string str2
as argument to the method as shown below.
str1.endsWith(str2)
endsWith() method returns a boolean value of true if the string str1
ends with the string str2
, or false if not.
Examples
1. Check if string ends with “efg”
In this example, we will take a string in str1
, and check if it ends with the value in the string str2
using String.endsWith() method.
Kotlin Program
fun main(args: Array<String>) {
val str1 = "abcdefg"
val str2 = "efg"
val result = str1.endsWith(str2)
println("endsWith() returns : " + result)
if( result ) {
println("String ends with specified string.")
} else {
println("String does not end with specified string.")
}
}
Output
endsWith() returns : true
String ends with specified string.
2. Negative Scenario
In this example, we will take a string in str1
, and check if it ends with the value in string str2
using String.endsWith() method.
Kotlin Program
fun main(args: Array<String>) {
val str1 = "abcdefg"
val str2 = "mno"
val result = str1.endsWith(str2)
println("endsWith() returns : " + result)
if( result ) {
println("String ends with specified string.")
} else {
println("String does not end with specified string.")
}
}
Since, we have taken string values in str1
and str2
such that str1
does not end with specified string value str2
, the method returns false.
Output
endsWith() returns : false
String does not end with specified string.
Conclusion
In this Kotlin Tutorial, we learned how to check if the given string ends with specified string value, using String.endsWith() method, with the help of Kotlin example programs.