Get last character in String in Kotlin
To get the last character in given string in Kotlin, you can use String.last()
function.
Call the last()
function on the given string str
.
str.last()
The function returns the last character in the string. But, if the string is empty, the function throws NoSuchElementException
.
Examples
Get last character in the string
In the following program, we take a string in str
and get the last character in this string using String.last()
function.
Kotlin Program
fun main(args: Array<String>) {
val str = "Hello World"
val lastChar = str.last()
println("Last Character : $lastChar")
}
Output
Last Character : d
Check if string is not empty before getting the last character
We can make a check if the string is not empty, and then get the last character. This way we can make sure that no Exception is thrown, and also we can look into doing something when the string is empty.
Kotlin Program
fun main(args: Array<String>) {
val str = "Hello World"
if (str.isNotEmpty()) {
val lastChar = str.last()
println("Last Character : $lastChar")
} else {
println("String is empty.")
}
}
Output
Last Character : d