Trimming strings in Scala

Try

val str = "  foo  "
str.trim

and have a look at the documentation. If you need to get rid of the , character, too, you could try something like:

str.stripPrefix(",").stripSuffix(",").trim

Another way to clean up the front-end of the string would be

val ignoreable = ", \t\r\n"
str.dropWhile(c => ignorable.indexOf(c) >= 0)

which would also take care of strings like ",,, ,,hello"

And for good measure, here’s a tiny function, which does it all in one sweep from left to right through the string:

def stripAll(s: String, bad: String): String = {

    @scala.annotation.tailrec def start(n: Int): String = 
        if (n == s.length) ""
        else if (bad.indexOf(s.charAt(n)) < 0) end(n, s.length)
        else start(1 + n)

    @scala.annotation.tailrec def end(a: Int, n: Int): String =
        if (n <= a) s.substring(a, n)
        else if (bad.indexOf(s.charAt(n - 1)) < 0) s.substring(a, n)
        else end(a, n - 1)

   start(0)
}

Use like

stripAll(stringToCleanUp, charactersToRemove)

e.g.,

stripAll("  , , , hello , ,,,, ", " ,") => "hello"

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)