简体   繁体   English

使用String#split()拆分表达式

[英]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表达式给出时却不是。

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. 第一个是您的第二个String[]与第一个具有相同的变量名。 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. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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