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]) = 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(_))

Post new comment

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