Trimming strings in Scala

前端 未结 5 1928
无人共我
无人共我 2020-12-25 10:19

How do I trim the starting and ending character of a string in Scala

For inputs such as \",hello\" or \"hello,\", I need the output as

5条回答
  •  隐瞒了意图╮
    2020-12-25 11:06

    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"
    

提交回复
热议问题