【发布时间】:2011-02-16 17:22:51
【问题描述】:
我喜欢转换字符串,例如:
String data = "1|apple,2|ball,3|cat";
变成这样的二维数组
{{1,apple},{2,ball},{3,cat}}
我已经尝试使用split("") 方法但仍然没有解决方案:(
谢谢..
启
【问题讨论】:
我喜欢转换字符串,例如:
String data = "1|apple,2|ball,3|cat";
变成这样的二维数组
{{1,apple},{2,ball},{3,cat}}
我已经尝试使用split("") 方法但仍然没有解决方案:(
谢谢..
启
【问题讨论】:
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]]"
【讨论】: