用Java中的String构建一个锯齿状数组



我必须编码这个"从String:创建矩阵

* The string if formatted as follow:
*  - Each row of the matrix is separated by a newline
*    character n
*  - Each element of the rows are separated by a space
*  For example, the String "0 1n2 3" represent the
*  matrix:
[0 1]
[2 3]

在练习中,矩阵可以是"矩阵";锯齿阵列";这是我的代码:

int[][] tab = null 
int compteur = 0
int position = 0
for (int i = 0; i < s.length(); i++) {
char l = s.charAt(i);
String p = String.valueOf(l);
if (Character.isDigit(s.charAt(i))) {
tab[compteur][position] = s.charAt(i);
position++;
else if(p.equals("/n")) {
position = 0;
compteur ++;
}
}
return tab

@Lionel Ding的解决方案当然会起作用,但值得一提的是,使用流可以说更优雅。然而,逻辑将保持不变-您按n字符拆分字符串,然后按"字符拆分每一行,将各个字符串解析为ints,并将结果收集到int[][]:

private static int[][] toMatrix(String s) {
return Arrays.stream(s.split("n"))
.map(line -> Arrays.stream(line.split(" "))
.mapToInt(Integer::parseInt).toArray())
.toArray(int[][]::new);
}

以下是代码:

public static int[][] method(String s) {
String[] x = s.split("n");
int[][] out = new int[x.length][x[0].split(" ").length];
for (int i = 0; i < x.length; i++) {
String[] y = x[i].split(" ");
for (int j = 0; j < y.length; j++) {
out[i][j] = Integer.parseInt(y[j]);
}
}
return out;
}

在:

String s = "0 1n2 3n4 5"

输出:

int[][] array = [0 1],[2 3],[4 5]

以上代码适用于方形矩阵,但这里的代码适用于任何类型的矩阵!:

public static int[][] method(String s) {
String[] x = s.split("n");
int max = Integer.MIN_VALUE;
for (String string : x) {
int l = string.split(" ").length;
max = l > max ? l : max;
}
int[][] out = new int[x.length][max];
for (int i = 0; i < x.length; i++) {
String[] y = x[i].split(" ");
for (int j = 0; j < y.length; j++) {
out[i][j] = Integer.parseInt(y[j]);
}
}
return out;
}

在:

String s = "0 1n2 3n4 5 6n1"

输出:

int[][] array = [0 1 0],[2 3 0],[4 5 6],[1 0 0]

最新更新