Trim leading whitespace characters using trimMargin in Kotlin

Trim leading whitespace characters using trimMargin in Kotlin :

Kotlin comes with a really handy function for string to trim leading whitespace characters easily. Known as trimMargin(), the definition of the function is as below :

fun String.trimMargin(marginPrefix: String = "|")
  • trimMargin is used to trim leading whitespace characters from each line of a string.
  • If the first and the last lines are blank, they will be removed.
  • Note that one parameter is passed to this method : marginPrefix. It trims all leading whitespace characters followed by marginPrefix. Default value of marginPrefix is ”|”.
  • marginPrefix should be non-blank.

Let me show you how trimMargin works with few examples :

Example 1 :

For a string with leading whitespace lines :

fun main(args: Array) {
    val originalString = """
    Hello
        World
    """
    
    println("-------")
    println(originalString) 
    println("-------")
    println(originalString.trimMargin())
    println("-------")
}

It will print the below output :

-------

    Hello
        World

-------
    Hello
        World
-------

kotlin trim leading whitespace

As you can see that only the first and the last empty strings were removed. Because, trimMargin trims whitespace characters followed by marginPrefix. Here marginPrefix is ”|” by default.

Example 2 :

fun main(args: Array) {
    val originalString = """
    |Hello
        |World
    """

    println("-------")
    println(originalString) 
    println("-------")
    println(originalString.trimMargin())
    println("-------")
}

Output will be :

-------

    |Hello
        |World

-------
Hello
World
-------

As you can see that this example is same as the previous one but the only difference is that we have added ”|” as the marginPrefix. So, the leading whitespace characters are removed. kotlin trim leading whitespace

Example 3 :

Now, let’s try with a different marginPrefix :

fun main(args: Array) {
    val originalString = """
    %Hello
        %World
    """

    println("-------")
    println(originalString) 
    println("-------")
    println(originalString.trimMargin("%"))
    println("-------")
}

Output :

-------

    %Hello
        %World

-------
Hello
World
-------

In this example, we have used a different marginPrefix ”%”. We have also passed this marginPrefix to the trimMargin function to successfully trim the leading whitespace characters. kotlin trim leading whitespace

Conclusion :

As you can see that trimMargin is really a useful function in kotlin for removing the leading whitespace characters of a string. Always keep in mind that marginPrefix is ”|” by default. If you are have a different marginPrefix, pass it as an argument to the trimMargin function.

You might also like :