我喜欢转换字符串,例如:
String data = "1|apple,2|ball,3|cat";
进入像这样的二维数组
{{1,apple},{2,ball},{3,cat}}
我尝试使用split("")
方法,但仍然没有解决方案:(
谢谢..
启
答案 0 :(得分:22)
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]]"
非常直截了当,但String.split
采用正则表达式,因此元字符|
需要转义。
Arrays.deepToString
和Arrays.deepEquals
用于多维数组如果您知道将有多少行和列,则可以预先分配String[][]
并使用Scanner
,如下所示:
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]]"