Kotlin – Trim String

Trim a Substring in Kotlin

To trim whitespaces from the edges of a string in Kotlin, you can use String.trim() function.

Call trim() function on the given String object str.


trim() function returns a new string by removing all the whitespaces characters from the starting and ending of the string. The whitespace characters in between the non-space character are left as is.


Trim string " Hello World "

Consider a scenario where we get a string with some spaces at the edges of the string, and we would like to remove these spaces.

Kotlin Program

fun main() {
    val str = "    Hello World  "
    val resultString = str.trim()


Hello World