Kotlin Remove Leading and Trailing Whitespaces Example

In this Kotlin example,  We use trim(), trimEnd() and trimStart() methods to remove leading and trailing whitespaces.

Remove leading and trailing whitespaces

The example presents methods for stripping white spaces from a string.
package net.javaguides.kotlin.examples

fun main(args: Array < String > ) {

    val s = " Source Code Examples.Net     "

    println("s has ${s.length} characters")

    val s1 = s.trimEnd()
    println("s1 has ${s1.length} characters")
    println("s1 -> " + s1)

    val s2 = s.trimStart()
    println("s2 has ${s2.length} characters")
    println("s2 -> " + s2)

    val s3 = s.trim()
    println("s2 has ${s3.length} characters")
    println("s3 ->  ${s3}")
s has 30 characters
s1 has 25 characters
s1 ->  Source Code Examples.Net
s2 has 29 characters
s2 -> Source Code Examples.Net     
Source Code Examples.Net
s2 has 24 characters
s3 ->  Source Code Examples.Net
The trimEnd() method removes trailing white spaces:
val s1 = s.trimEnd()
The trimStart() method removes leading white spaces:
val s2 = s.trimStart()
The trim() method removes both trailing and leading white spaces:
val s3 = s.trim()

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course