0

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;
}      
3
  • Which element are you trying to retrieve? Commented Feb 28, 2017 at 7:50
  • See How to split a string by a string in Scala. Commented Feb 28, 2017 at 7:50
  • so what's your problem exactly? since s.split("\\s+"); should work in Scala!? Just assign it to a variable or whatever you wanna do and read the array elements: val arr = s.split("\\s+"); Commented Feb 28, 2017 at 7:59

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't need the result var. Just conclude with the match statement.
tyvm! This is very helpful :>
0

Use pattern matching to extract the string items and also to match the operator,

def eval(s: String): Double = {
  val Array(left, op, right, _*) = s.split("\\s+")
  (left.toDouble, op, right.toDouble) match {
    case (a, "+", b) => a+b
    case _           => Double.NaN  // error value
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.