How to left-trim and right-trim strings in Scala?

Scala | Trimming strings: Here, we are going will learn how to left-trim and right-trim strings in Scala programming language?
Submitted by Shivang Yadav, on April 24, 2020 [Last updated : March 10, 2023]

Scala – Trimming a string

Trimming a string is the method of removing extra spaces from the string. It can be left removal, right removal, or removal of all spaces from the string.

To remove blank spaces from a string, Scala provides a trim() method. The trim() will remove spaces from both sides, i.e. before the characters(leading) and from the end(trailing).

Syntax

    string.trim()

The method doesn't accept any parameter and returns a string with spaces removed from it.

Scala code to remove spaces string using trim()

object myObject {
    def main(args: Array[String]) {
        val string = " Hello! Learn scala programming at IncludeHelp    "
        println("Orignal string is '" + string + "' with leading and trailing spaces")
        val trimmedString = string.trim
        println("The trimmed string is '" + trimmedString + "'")
    }
}

Output

Orignal string is ' Hello! Learn scala programming at IncludeHelp    ' with leading and trailing spaces
The trimmed string is 'Hello! Learn scala programming at IncludeHelp'

Trimming string from left or right

We can optionally trim a string is scala from the left (removing leading spaces) called left-trim and from the right (removing trailing spaces) called right-trim.

This is done using the replaceAll() methods with regex. We will find all the space (right/left) using the regular expression and then replace them with "".

Scala code to remove left and right spaces

object MyClass {
    def main(args: Array[String]) {
        val string = "       Hello! Learn scala programming at IncludeHelp      "
        println("The string is '" + string + "'")
        val leftTrimString = string.replaceAll("^\\s+", "")
        println("Left trimmed string is '" + leftTrimString + "'")
        val rightTrimString = string.replaceAll("\\s+$", "")
        println("Right trimmed string is '" + rightTrimString + "'")
    }
}

Output

The string is '       Hello! Learn scala programming at IncludeHelp      '
Left trimmed string is 'Hello! Learn scala programming at IncludeHelp      '
Right trimmed string is '       Hello! Learn scala programming at IncludeHelp'

Scala String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.