ps0604 ps0604 - 3 months ago 19
Scala Question

How to remove spaces between parentheses in Scala

Given the string:

val s = "[ a + 5 + ( 1 + 2)]"


I need to convert it to:

[ a + 5 + (1+2)]


How should I achieve this? Regex?

Spaces should be removed from within parentheses: any other spaces in the string should remain as-is.

Another example:

aaa bbb ccc ( 1 + 2 )


should return:

aaa bbb ccc (1+2)


Another example:

( 1 + 2 ) + ( 3 + 4 )


should return:

(1+2) + (3+4)

Answer

Try this.

def squeezeParens(str: String): String =
  str.foldLeft(("",0)){ case ((result, depth),c) => c match {
    case '('              => (result + c, depth+1)
    case ')' if depth > 0 => (result + c, depth-1)
    case ' ' if depth > 0 => (result,     depth)
    case  _               => (result + c, depth)
  }}._1

It should remove all space characters after the first '(' until it finds the matching ')'. It removes spaces even if the matching ')' is not found.