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

As a brief note, here are 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+$", "")

If I ever write a Scala StringUtils class, I’ll be sure to include those functions in that class.

Remove all blank strings from Scala sequences

In a related “string utilities” 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.)

How to trim all strings in a Scala sequence

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

def trim(strings: Seq[String]) = strings.map(_.trim)

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

def removeLeadingSpaces(strings: Seq[String]) = strings.map(ltrim(_))
def removeTrailingSpaces(strings: Seq[String]) = strings.map(rtrim(_))