What is trim() in Scala?

The trim() method is used to remove all the leading and trailing spaces that are present in the string. For example, if the string looks like, " Hello World " then there is a lot of empty space before the term “Hello” and after the term “World”.

The method trim() is used to remove these spaces.

Trim applied on some data

Title

Trim

" Hello World "

"Hello World"

" Lord of the rings "

"Lord of the rings"

" Fight club "

"Fight club"

Syntax

string.trim()

Using this method returns a string without any trailing of leading white spaces.

Code

Let’s understand it better with a coding example.

object Main extends App {
// apply trim on a string
val data = " Hello World ".trim()
// Display resultant data
println(data)
val data1 = "Lord of the rings ".trim()
// Display resultant data
println(data1)
}
Copyright ©2024 Educative, Inc. All rights reserved