更新时间:2023-02-03 08:59:51
字符串数据=1 |苹果,2 |球,3 |猫;
串[]行= data.split(,); 的String [] [] =矩阵新的String [rows.length] [];
INT R = 0;
对于(字符串行:行){
矩阵[R +] = row.split(\\\\ |);
} 的System.out.println(矩阵[1] [1]);
//输出球 的System.out.println(Arrays.deepToString(矩阵));
//输出[[1,苹果],[2,球],[3,猫]]
pretty除了String.split$c$c>需要正则表达式,那么元字符 |
需要转义
Arrays.deepToString
和 Arrays.deepEquals
多维数组如果你知道有多少行和列会出现,你可以pre-分配的String [] []
,并使用扫描仪
如下:
扫描仪SC =新的扫描仪(数据).useDelimiter([,|]);
最终诠释M = 3;
最终诠释N = 2;
的String [] [] =矩阵新的String [M] [N];
对于(INT R = 0;为r,M,R ++){
对于(INT C = 0; C< N,C ++){
矩阵[R] [C] = sc.next();
}
}
的System.out.println(Arrays.deepToString(矩阵));
//输出[[1,苹果],[2,球],[3,猫]]
I like to convert string for example :
String data = "1|apple,2|ball,3|cat";
into a two dimensional array like this
{{1,apple},{2,ball},{3,cat}}
I have tried using the split("")
method but still no solution :(
Thanks..
Kai
String data = "1|apple,2|ball,3|cat";
String[] rows = data.split(",");
String[][] matrix = new String[rows.length][];
int r = 0;
for (String row : rows) {
matrix[r++] = row.split("\\|");
}
System.out.println(matrix[1][1]);
// prints "ball"
System.out.println(Arrays.deepToString(matrix));
// prints "[[1, apple], [2, ball], [3, cat]]"
Pretty straightforward except that String.split
takes regex, so metacharacter |
needs escaping.
Arrays.deepToString
and Arrays.deepEquals
for multidimensional arraysIf you know how many rows and columns there will be, you can pre-allocate a String[][]
and use a Scanner
as follows:
Scanner sc = new Scanner(data).useDelimiter("[,|]");
final int M = 3;
final int N = 2;
String[][] matrix = new String[M][N];
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
matrix[r][c] = sc.next();
}
}
System.out.println(Arrays.deepToString(matrix));
// prints "[[1, apple], [2, ball], [3, cat]]"