user21478621 user21478621 -4 years ago 160
Scala Question

Scala how to split string and store into array?

I am currently writing a program that read a string like "2 + 2". It should be split regarding the spaces and store into an Array like Array(2, +, 2). However, I am not sure how to do it within a method (since I usually work in Scala interpreter), access to the result after I split it. I know that in java, you can do String[] arr = string.split("\s+").

def eval(s: String): Double = {
var result = 0;
s.split("\\s+");
//how do i retrieve the element that was split?
// I am trying to retrieve, like the above example, the 2 and 2
// perform an addition on them so the method will return a double
result;
}

Answer Source

Splitting is same as in java, you can read the answers here.

Only thing you are missing is accessing the array which is done with array(index)

def eval(s: String): Double = {
  val operands = s.split("\\s+")
  operands(0).toDouble + operands(2).toDouble //the last statement is return statement
}

assert(eval("2 + 2") == 4)

The above will always do addition even if you do eval("2 - 2") == 4

But if you want to have all operations(+, -) then do pattern match on your operator which is index 1.

def eval(s: String): Double = {
  val operandsWithOperator = s.split("\\s+")

  operandsWithOperator(1) match {
    case "+" => operandsWithOperator(0).toDouble + operandsWithOperator(2).toDouble
    case "-" => operandsWithOperator(0).toDouble - operandsWithOperator(2).toDouble
    case "*" => operandsWithOperator(0).toDouble * operandsWithOperator(2).toDouble
    case "/" => operandsWithOperator(0).toDouble / operandsWithOperator(2).toDouble
  }
}

assert(eval("2 + 2") == 4)
assert(eval("2 - 2") == 0)
assert(eval("2 * 3") == 6)
assert(eval("2 / 2") == 1)

And if you want more than two operands, then recurse.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download