0

Ok, so the assignment is that I take the Lisp expression:

'(A B C D)

And turn it into

'(D C B A)

in 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?

2 Answers2

1

the sub-string terminated by the char ' is an empty sub-string, the string terminated by ( is also an empty sub-string

the method you are using breaks up a String into sub-strings that are terminated by a delimiter.

Ammar S
  • 91
  • 8
0

To put it simply your String looks like this when split:

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

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

P.S. You've also set the ')' character twice in your regex

Andrei Fierbinteanu
  • 7,656
  • 3
  • 31
  • 45