×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

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

By IncludeHelp Last updated : October 22, 2024

Description and Usage

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: 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.