In this tutorial, you shall learn how to trim white spaces around a given string in Kotlin, using String.trim() function, with examples.

Kotlin – Trim White Spaces around String

To trim white spaces around a string in Kotlin, call trim() method on this String. trim() returns a new string with all the white space characters removed from the beginning and trailing ends of this string.


In the following example, we take a string in str, and trim the white spaces around it using trim() method.


fun main(args: Array<String>) {
    var str = "   hello world  "
    var result = str.trim()
    println("\"" + result + "\"")


"hello world"


In this Kotlin Tutorial, we learned how to trim white spaces around a string using String.trim() method, with the help of Kotlin example programs.