How to delete extra spaces from String in Scala? Scala String trim() Method

Here, we will learn about trim() method on strings which is used to remove extra spaces from strings in Scala. We will see the syntax and working examples of the method.
Submitted by Shivang Yadav, on January 27, 2021

String is an immutable collection that stores sequences of characters.

How to delete extra spaces from the string in Scala?

You can delete extra leading and trailing spaces from a string in Scala using trim() method.

Example:

string = 		"	   Scala     " 
trimmpedString = 	"Scala"

String trim() Method

The trim() method defined on Scala strings is used to remove extra space from the starting and ending of the string.

You can remove extra spaces, tabs spaces and new line characters using the trim method.

Syntax:

String_name.trim()

Parameters: The method does not accept any parameter.

Return Value: It returns a string which is the calling string after removing the leading and trailing spaces.

Example 1: Program to illustrate the working of our solution

object MyClass {
    def main(args: Array[String]) {
        val myString = "        Scala     "
        println("Original string is '" + myString + "'")
    
        val trimmedString = myString.trim()
        println("Trimmed String is '" + trimmedString + "'")
    }
}

Output:

Original string is '        Scala     '
Trimmed String is 'Scala'

Example 2: Program to illustrate trimming of newline and tabs using trim() method

object MyClass {
    def main(args: Array[String]) {
        val myString = "\n      Scala         "
        println("Original string is '" + myString + "'")
    
        val trimmedString = myString.trim()
        println("Trimmed String is '" + trimmedString + "'")
    }
}

Output:

Original string is '
      Scala         '
Trimmed String is 'Scala'




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.