How to Split a mathematical expression on operators as delimiters, while keeping them in the result?

前端 未结 5 1055
忘了有多久
忘了有多久 2020-11-29 09:36

I need to split an expression like

a+b-c*d/e 

and get a, b, c, d, e sepe

5条回答
  •  广开言路
    2020-11-29 10:19

    Besides the split approach, you could also use java.util.StringTokenizer:

     String myString = "a+b-c*d/e";
    
     List operatorList = new ArrayList();
     List operandList = new ArrayList();
     StringTokenizer st = new StringTokenizer(myString, "+-*/", true);
     while (st.hasMoreTokens()) {
        String token = st.nextToken();
    
        if ("+-/*".contains(token)) {
           operatorList.add(token);
        } else {
           operandList.add(token);
        }
     }
    
     System.out.println("Operators:" + operatorList);
     System.out.println("Operands:" + operandList);
    

    Result:

    Operators:[+, -, *, /]
    Operands:[a, b, c, d, e]
    

提交回复
热议问题