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!

Load comments ↻





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