How to left-trim and right-trim strings in Scala

A few examples of how to implement left-trim and right-trim on strings in Scala:

def ltrim(s: String) = s.replaceAll("^\\s+", "")
def rtrim(s: String) = s.replaceAll("\\s+$", "")

In a related note, here’s a method that removes all blank strings from a Seq, List, or Array of strings:

def removeBlankStrings(strings: Seq[String]): Seq[String] = {
    for {
        s <- strings
        if !s.trim.equals("")
    } yield s

I wrote that method when I was half-awake, then realized that I was writing a filter method. An even better approach is to use the filter or filterNot method:

def removeBlankStrings(strings: Seq[String]) = strings.filterNot(_.trim.equals(""))

(When I say “better”, I mean that the code does the same thing, and it’s more concise and easier to read.

You can trim all the strings in a Scala sequence like this:

def trim(strings: Seq[String]) =

Finally, you can left trim and right trim all strings in a sequence like this:

def removeLeadingSpaces(strings: Seq[String]) =
def removeTrailingSpaces(strings: Seq[String]) =

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.