简体   繁体   English

在Java中将字符串转换为二维字符串数组

[英]Convert string into two dimensional string array in Java

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 :( 我尝试过使用split("")方法,但仍然没有解决方案:(

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 | 非常简单,除了String.split采用正则表达式,所以元字符| needs escaping. 需要逃避。

See also 也可以看看


Alternative 替代

If you know how many rows and columns there will be, you can pre-allocate a String[][] and use a Scanner as follows: 如果您知道将有多少行和列,您可以预先分配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]]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM