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

Kotlin – Remove last character in String

To remove last character in string in Kotlin, you can use String.dropLast() function.

Call the dropLast() function on the string, and pass 1 as argument, since we want to remove only one character from the end of this string. The function returns the contents of this string with the last character removed.

Syntax

If str is the given string, then the syntax of the statement to remove the last character is

</>
Copy
str = str.dropLast(1)

Example

In the following program, we take a string in str, remove the last character from the string, and print the output.

Main.kt

</>
Copy
fun main() {
    var str = "helloworld"
    str = str.dropLast(1)
    println(str)
}

Output

helloworl

Explanation

h e l l o w o r l d
0 1 2 3 4 5 6 7 8 9
                  d <- last character
h e l l o w o r l   <- resulting string

Conclusion

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