0

I am making a calculator sort of app for android and got stuck for evaluating expression which comes by entering numbers and different signs.I have string as "10+5-35*2+80/4" and want to separate all numbers and signs so that I can solve the expression.

more specific.... number can be any number between [0-9] of any digit and any operator can be there.

2 Answers2

0

You can iterate over the string and use the following:

for(Character ch : inputString.toCharArray())
    if (Character.isDigit(ch))
        // ...
nitishagar
  • 9,038
  • 3
  • 28
  • 40
0
    List<String> numbers = new ArrayList<>();
    List<String> operators = new ArrayList<>();
    String str = "1+2/300%4";
    char[] strCharArray = str.toCharArray();
    StringBuilder numbersSb = new StringBuilder();
    for (int i = 0; i < strCharArray.length; i++) {
        if (Character.isDigit(strCharArray[i])) {
            numbersSb.append(strCharArray[i]);
        } else {
            operators.add(String.valueOf(strCharArray[i]));
            numbers.add(numbersSb.toString());
            numbersSb = new StringBuilder();
        }
        if (i == strCharArray.length - 1 && !numbersSb.toString().isEmpty()) {
            numbers.add(numbersSb.toString());
        }
    }
Robert Bain
  • 9,113
  • 8
  • 44
  • 63