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

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.

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'

Scala String Programs »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.