java double split to String[ ][ ]

Aspwil enson :

I'm having a problem coming up with a way to take a string and use .split() twice to make a nested array.

For example if I have the string 1|2|3#1|2 and then I use split("#"), I end up with: [ "1|2|3" , "1|2" ].

I then want to .split("|") the inside strings somehow, so I end up with: [ [1,2,3] , [1,2] ].

But it needs to be a String[][].

I already tried using an ArrayList as the as the external one so I had an ArrayList and then just used .add() to build it up with each of the internal arrays.

But then I could not figure out how to convert it to a String[][].

I'm probably missing something obvious but I've been trying for around an hour and have had no luck.

T.J. Crowder :

You're on the right track. Once you've got the String[] after the first split, allocate your String[][] and then fill it in in a loop, splitting the strings in the first array:

String str = "1|2|3#1|2";
String[] strs = str.split("#");
String[][] result = new String[strs.length][];
for (int i = 0; i < strs.length; ++i) {
    result[i] = strs[i].split("\\|");
}

Live Example

Note that since split accepts a string defining a regular expression, you have to escape the | in it (because | has special meaning in regular expressions). You escape things in regular expressions with a backslash. Since I'm using a string literal to write the regular expression, to put a backslash actually in the string, I have to escape it (with another backslash).

Or with streams (with thanks to ChenZhou for pointing 80% of the way there), got the rest of the way thanks to the JavaDoc:

String[] strs = "1|2|3#1|2".split("#");
String[][] result = Stream.of(strs).map(e -> e.split("\\|")).toArray(String[][]::new);

Live Example

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322561&siteId=1