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

Kotlin – Check if String Ends with Specified Character

To check if String ends with specified character in Kotlin, use String.endsWith() method.

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

</>
Copy
str1.endsWith(ch)

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

Examples

1. Check if string ends with ‘g’

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

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    val str1 = "abcdefg"
    val ch = 'g'
    val result = str1.endsWith(ch)
    println("endsWith() returns  : " + result)
    if( result ) {
        println("String ends with specified character.")
    } else {
        println("String does not end with specified character.")
    }
}

Output

sWith() returns  : true
String ends with specified character.

2. Negative Scenario

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

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    val str1 = "abcdefg"
    val ch = 'm'
    val result = str1.endsWith(ch)
    println("endsWith() returns  : " + result)
    if( result ) {
        println("String ends with specified character.")
    } else {
        println("String does not end with specified character.")
    }
}

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

Output

endsWith() returns  : false
String does not end with specified character.

Conclusion

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