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.

Example

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

Main.kt

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

Output

"hello world"

Conclusion

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.