简体   繁体   English

如何将逗号分隔的字符串转换为 Java 中的二维数组?

[英]How to covert comma separated string to a 2D array in Java?

For example I have some comma separated strings "aron, IA52, 20" "john, IA61, 23" "kleo, IA32, 42" How can I convert them to a 2 dimensional array in the easiest way possible?例如,我有一些逗号分隔的字符串 "aron, IA52, 20" "john, IA61, 23" "kleo, IA32, 42" 如何以最简单的方式将它们转换为二维数组?

As already pointed out in comments, you should use split() while iterating over your comma separated string list and populate your array accordingly.正如评论中已经指出的那样,您应该在迭代逗号分隔的字符串列表时使用split()并相应地填充您的数组。 Here is sample code to give you some idea:这是示例代码,可以为您提供一些想法:

List<String> input = Arrays.asList("aron, IA52, 20", "john, IA61, 23", "kleo, IA32, 42");
String[][] array = new String[3][3];
int row = 0;

// Loop Over Comma Separated List and split each string to populate 2D array
for (String commaSeparatedStr : input) {
    String[] parts = commaSeparatedStr.split(",");
    System.arraycopy(parts, 0, array[row], 0, parts.length);
    row++;
}

// Print array
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++)
        System.out.print(array[i][j]);
    System.out.println();
}

This prints:这打印:

aron IA52 20
john IA61 23
kleo IA32 42

The provided function will parse the string to the 2D matrix.提供的 function 会将字符串解析为二维矩阵。 Below is the format of the string that you need to provide to this function.下面是您需要提供给这个 function 的字符串的格式。

1.2,2.3,3.5\n3.1,4.70,5.0

function function

public double[][] parseStingToArray(String str) {
        System.out.println(str);
        String arr1[] = str.split("\n");

        double[][] ans = new double[arr1.length][];

        for (int i = 0; i < arr1.length; i++) {
            String[] col = arr1[i].split(",");
            ans[i] = new double[col.length];
            for (int j = 0; j < col.length; j++) {
                ans[i][j] = Double.parseDouble(col[j]);
            }
        }

        doubleArray = ans;
        return ans;
    }

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

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