Kotlin – Delete Last Character in String

Delete last character in String in Kotlin

To delete the last character in a given string in Kotlin, you can use String.substirng() function. The string without the last character is same as the substring from index=0 to index=str.length-1.

Find the substring from index=0 to index=str.length-1

str.substring(0, str.length - 1)

Examples

Delete last character in the message

In the following program, we take a message as string in str and delete the last character in the string.

Kotlin Program

fun main() {
    val str = "apple"
    val resultString = str.substring(0, str.length - 1)
    println(resultString)
}

Output

appl

Explanation

a  p  p  l  e  <- str
0  1  2  3  4  <- indices

            e  <- delete last character

a  p  p  l
str(0,    4)