Reputation: 31
Suppose a string s = "1 2\n3 4"
; the goal is to create a matrix
$ \begin{bmatrix}
1 & 2 \\
3 & 4
\end{bmatrix} $
I have the following code :
public static String[] buildFrom(String s) {
String lines[] = s.split("\\r?\\n");
String newlines[] = new String[lines.length];
int i;
for (i = 0; i < lines.length; i++)
newlines[i] = Arrays.toString(lines[i].split("\\s+"));
return newlines;
The output is [[1, 2], [3, 4]]
It seems to be a String[], However I need a String[][]. The issue seems to be the usage of Arrays.toString
but I don't know what else I could use.
Any help would be welcome.
Upvotes: 0
Views: 58
Reputation: 4699
This will return you a String[][]
as you seem to want:
public static String[][] buildFrom(String s) {
String[] lines = s.split("\\R");
String[][] matrix = new String[lines.length][];
for (int i = 0; i < lines.length; i++) {
matrix[i] = lines[i].split("\\s+");
}
return matrix;
}
You may want to do additional checks to ensure your matrix is valid such as all rows having the same number of elements.
Your main issue is that you were declaring your output variable to be a String[]
rather than a String[][]
like you really wanted and thus you could only set its indices (the rows in this case) to be a String
rather than a String[]
. So it seems you used Arrays.toString(String[])
to convert the String[]
you wanted for the row into a String
to get around that compile error.
Upvotes: 1