In this tutorial, you shall learn how to get the last character in a given string in Kotlin, using String.last() function, with examples.

Kotlin – Get Last Character in String

To get last character in string in Kotlin, we can use String.last() function. Call the last() function on the given string, and the function returns the last character in the string.

Syntax

If str is the given string, then the syntax of the function call to get the last character in this string is

</>
Copy
str.last()

Example

In the following program, we take a string in str, get the last character in the string, and print it to output.

Main.kt

</>
Copy
fun main() {
    var str = "hello world"
    var lastChar = str.last()
    println("Last Character : $lastChar")
}

Output

Last Character : d

Conclusion

In this Kotlin Tutorial, we learned how to get the last character in a string using String.last() function.