[英]Splitting Lisp expression in java
Ok, so the assignment is that I take the Lisp expression: 好的,所以分配是我采用Lisp表达式:
'(A B C D)
And turn it into 然后变成
'(D C B A)
in Java. 在Java中。 To do this, I have this code:
为此,我有以下代码:
String[] items = input.split(" |\\(|\\)|'");
int y = 0;
for (String x : items){ //this part is purely for debugging
System.out.println(y + " " + x);
y++;
}
So that it splits it by a space, (, ), and '. 这样就可以用(,,)和'分隔它。 The output I should be getting is
我应该得到的输出是
0 A
1 B
2 C
3 D
But for some reason, The output I get is 但是由于某种原因,我得到的输出是
0
1
2 A
3 B
4 C
5 D
Why does this happen? 为什么会这样? Also, does anyone has a suggestion for a better way of doing this?
另外,有人建议采用更好的方法吗?
the sub-string terminated by the char '
is an empty sub-string, the string terminated by (
is also an empty sub-string 以char
'
结尾的子字符串是一个空子字符串,以(
结尾的字符串也是一个空子字符串
the method you are using breaks up a String into sub-strings that are terminated by a delimiter. 您使用的方法将一个String拆分为多个由分隔符终止的子字符串。
To put it simply your String looks like this when split: 简单地说,拆分时您的String如下所示:
"" (emptyString) between start of string and first delimiter match "'"
"" between first delimiter "'" and second delimiter "("
"A" between second delimiter "(" and third delimiter " " (space)
"B" between third delimiter " " and fourth delimiter " "
"C" between fourth delimiter " " and fifth delimiter " "
"D" between fifth delimiter " " and sixth delimiter ")"
Since you're not providing a limit to the number of matches, the split removes trailing empty spaces by default. 由于您没有限制匹配数,因此默认情况下,拆分会删除尾随的空格。 If you would call it using .split(regex, -1), it wouldn't ignore them and also give the following elements:
如果使用.split(regex,-1)调用它,它将不会忽略它们,并提供以下元素:
"" between sixth delimiter ")" and the end of the string
PS You've also set the ')' character twice in your regex PS您还需要在正则表达式中两次设置')'字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.