本文介绍了转换成字符串在Java中的二维字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换为字符串,例如:

 字符串数据=1 |苹果,2 |球,3 |猫;

成二维阵列这样

  {{1,苹果},{2,球},{3,猫}}

我已经使用拆分()方法,但仍然无解试过:(

谢谢..


解决方案

 字符串数据=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除了<$c$c>String.split需要正则表达式,那么元字符 | 需要转义

另请参见





    • 使用 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&LT; 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.

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:

    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]]"

这篇关于转换成字符串在Java中的二维字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:19