Q:

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

belongs to collection: Scala String Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program 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 "".

Program 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'

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to get date, month and year as string or numbe... >>
<< How to create a range of characters in Scala?...