To get the last character of a given string in Kotlin, you can use the indexing operator with the length of the string minus one.
In this example,
str1
with a value of "Hello World"
.[]
with str1
and str1.length - 1
to get the last character.fun main() {
val str1 = "Hello World"
val lastChar = str1[str1.length - 1]
print("Last character of the string is: $lastChar")
}
Last character of the string is: d
In this example,
str2
with a value of "apple"
.[]
with str2
and str2.length - 1
to get the last character.fun main() {
val str2 = "apple"
val lastChar = str2[str2.length - 1]
print("Last character of the string is: $lastChar")
}
Last character of the string is: e
In this tutorial, we learned How to get Last Character in String in Kotlin language with well detailed examples.