简体   繁体   中英

Splitting expression with String#split()

I want to convert a infix operation to postfix operation. My code works when the input is given as already split expression through an array. But it doesn't when the input is given as the raw String expression.

String[] exp={"23","+","32"}//this works
String str="23 + 32";
String[]exp=str.split("//s+" );//this doesn't work

我认为您必须使用反斜杠而不是斜杠:

String[] exp = str.split("\\s+");

You had 2 issues I could see in your code. The first is that your second String[] has the same variable name as your first. The second is that you were using forward-slashes instead of back-slashes.

    String[] exp = {"23","+","32"};
    String str = "23 + 32";
    String[] exp2 = str.split("\\s+"); // or " +"

    System.out.println(Arrays.toString(exp));
    System.out.println(Arrays.toString(exp2));

The above is working correctly for me.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM