0

好的,所以任务是我采用 Lisp 表达式:

'(A B C D)

并把它变成

'(D C B A)

在爪哇。为此,我有以下代码:

String[] items = input.split(" |\\(|\\)|'");
int y = 0;
for (String x : items){ //this part is purely for debugging
    System.out.println(y + " " + x);
    y++;
}

这样它就可以用空格、(, ) 和 ' 来分割它。我应该得到的输出是

0 A
1 B
2 C
3 D

但由于某种原因,我得到的输出是

0
1
2 A
3 B
4 C
5 D

为什么会这样?另外,有没有人建议更好的方法来做到这一点?

4

2 回答 2

1

由 char 终止的子字符串'是空子串,以 char 结尾的字符串(也是空子串

您使用的方法将字符串分解为由分隔符终止的子字符串。

于 2015-02-04T04:11:08.953 回答
0

简单地说,你的字符串在拆分时看起来像这样:

"" (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 ")"

由于您没有限制匹配的数量,因此默认情况下拆分会删除尾随空格。如果您使用 .split(regex, -1) 调用它,它不会忽略它们并提供以下元素:

"" between sixth delimiter ")" and the end of the string

PS您还在正则表达式中设置了两次“)”字符

于 2015-02-04T10:39:28.140 回答