-4

When the text was '2+3+5+1', the logic was easy

  1. Split('+') so the string is converted to an array.
  2. loop over the array and calculate the sum. check the code below
void main() {
const text = '2+3+5+1';
final array = text.split('+');
  int res =0;
  for (var i=0; i<= array.length -1; i++){
   res+=int.parse(array[i]);;
  }
print(array);
print(res);
} 

Now this String "2+3-5+1" contains minus. how to get the right response using split method? I am using dart. note: I don't want to use any library (math expression) to solve this exercice.

Ayz
  • 181
  • 1
  • 9
  • Does [this](https://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript) help? – Tamir Abutbul Oct 18 '22 at 21:06
  • You could use a regular expression instead. Something like `text.split(new RegExp(r"[+\-*\/]"))` would split at every `+`, `-`, `*`, or `/` character. – Jesse Oct 18 '22 at 21:10
  • It may be easier to just read each character one by one rather than trying to split it though. Read a character, if it's a number, append it to a string. If it's a symbol, keep track of it and begin reading the next number. Once you've got two numbers, perform the operation on them and from then on use the result as the first number. If done correctly that should be pretty simple and give you the correct result. – Jesse Oct 18 '22 at 21:16
  • also [Evaluating a string as a mathematical expression in JavaScript](https://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript) – pilchard Oct 18 '22 at 21:22
  • 1
    Also, your code looks like c++, java and python at the same time – Konrad Oct 18 '22 at 21:35

3 Answers3

1

Use the .replace() method.

text = text.replace("-", "+-");

When you run through the loop, it will calculate (-).

Michael M.
  • 10,486
  • 9
  • 18
  • 34
0

I see 2 maybe 3 options, definitely there are hundreds

  1. You don't use split and you just iterate through the string and just add or subtract on the way. As an example

You have '2+3-5+1'. You iterate until the second operator (+ or -) on your case. When you find it you just do the operation that you have iterated through and then you just keep going. You can do it recursive or not, doesn't matter

"2+3-5+1" -> "5-5+1" -> "0+1" -> 1

  1. You use split on + for instance and you get [ '2', '3-5', '1' ] then you go through them with a loop with 2 conditions like

if(isNaN(x)) res+= x since you know it's been divided with a +

if(!isNaN(x)) res+= x.split('-')[0] - x.split('-')[1]

isNaN -> is not a number

Ofc you can make it look nicer. If you have parenthesis though, none of this will work

  1. You can also use regex like split(/[-+]/) or more complex, but you'll have to find a way to know what operation follows each digit. One easy approach would be to iterate through both arrays. One of numbers and one of operators
"2+3-5+1".split(/[-+]/) -> [ '2', '3', '5', '1' ]
"2+3-5+1".split(/[0-9]*/).filter(x => x)  ->  [ '+', '-', '+' ]

You could probably find better regex, but you get the idea

You can ofc use a map or a switch for multiple operators

Catalin Leca
  • 122
  • 10
0

You can split your string using regex text.split(/\+|\-/).

This of course will fail if any space is added to the string (not to mention *, / or even decimal values).

const text = '20+3-5+10';

const arr = text.split(/\+|\-/)

let tot = 0
for (const num of arr) {
  const pos = text.indexOf(num)

  if (pos === 0) {
    tot = parseInt(num)
  } else {
    switch (text.substr(text.indexOf(num) - 1, 1)) {
      case '+':
        tot += parseInt(num)
        break

      case '-':
        tot -= parseInt(num)
        break
    }
  }
}

console.log(tot)
GrafiCode
  • 3,307
  • 3
  • 26
  • 31