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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2786777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:51:39  来源:igfitidea点击:

Convert string into two dimensional string array in Java

javaarraysstring

提问by kaibuki

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

采纳答案by polygenelubricants

    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.splittakes regex, so metacharacter |needs escaping.

非常简单,除了String.split需要正则表达式,所以元字符|需要转义。

See also

也可以看看



Alternative

选择

If you know how many rows and columns there will be, you can pre-allocate a String[][]and use a Scanneras follows:

如果您知道将有多少行和列,则可以按如下方式预先分配 aString[][]并使用 a 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]]"