1

I'm implementing a game server and representing the game board as a string, take this state as an example:

String b = ", a36, a32, a26, a40, a295, a41, a49, /, , a16, a09, a68, a11, a99, ,"

I want to convert this string into the following string array:

[, a36, a32, a26, a40, a295, a41, a49, , , , a16, a09, a68, a11, a99, ]

I tried to use String.split:

String[] bArray = b.split("/|,");

This yields:

boardArray = [, a36, a32, a26, a40, a295, a41, a49, , , , a16, a09, a68, a11, a99]

It cuts off the last " " element in the array that I want. After modifying my code and manually adding the last element:

String[] bArray = b.split("/|,");
bArray = Arrays.copyOf(bArray, bArray.length + 1);
bArray[bArray.length - 1] = "";

This gives me the correct result, but this solution is inefficient. Does anyone have an idea how to do this more cleanly?

Monika
  • 301
  • 3
  • 12
  • The functional code you provided doesn't seem terribly inefficient. Maybe submit to the codereview stackexchange for ideas on how to improve instead of here. – h0r53 Jan 29 '20 at 22:16

3 Answers3

4

Try this:

b.split("/|,", -1);

this is split with limit parameter (the second one) and as documenation says:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Renato
  • 2,077
  • 1
  • 11
  • 22
1

Try loading to a List<String> and iterating through that list.

String b = ", a36, a32, a26, a40, a295, a41, a49, /, , a16, a09, a68, a11, a99, ,";
List<String> myList = Arrays.asList(b.split(","));
System.out.println(myList);

Output:

[,  a36,  a32,  a26,  a40,  a295,  a41,  a49,  /,  ,  a16,  a09,  a68,  a11,  a99,  ]
Renato
  • 2,077
  • 1
  • 11
  • 22
Siva S
  • 11
  • 2
0

As stated on a previous question java has this behaviour as default.

Sometimes you have to implement yourself new functionalities, but probably this is not a clean solution.

  • This seems more appropriate as a comment than an answer. Albeit, the question seems better suited for the codereview stackexchange. – h0r53 Jan 29 '20 at 22:17