首页 > 解决方案 > 将字符串值转换为 double 类型的二维数组

问题描述

我有一个字符串:

String stringProfile = "0,4.28 10,4.93 20,3.75";

我试图把它变成一个数组,如下所示:

double [][] values = {{0, 4.28}, {10, 4.93}, {20, 3.75}};

我已格式化字符串以删除任何空格并替换为逗号:

String stringProfileFormatted = stringProfile.replaceAll(" ", ",");

所以现在字符串stringProfileFormatted = "0,4.28,10,4.93,20,3.75";

然后我创建一个字符串数组:

String[] array = stringProfileFormatted.split("(?<!\\G\\d+),");

因此,对于 Array 中的每个元素,每 2 个逗号值的字符串。

不知道如何转换为二维数组。这甚至是正确的方法吗?

标签: javaarraysmultidimensional-array

解决方案


我会一步一步地解决这个任务。

首先,我会String用空格分割原始数据,然后用逗号分割结果,然后doubleDouble.parseDouble(String value).

public static void main(String[] args) {
    String stringProfile = "0,4.28 10,4.93 20,3.75";

    // split it once by space
    String[] parts = stringProfile.split(" ");

    // create some result array with the amount of double pairs as its dimension
    double[][] results = new double[parts.length][];

    // iterate over the result of the first splitting
    for (int i = 0; i < parts.length; i++) {
        // split each one again, this time by comma
        String[] values = parts[i].split(",");

        // create two doubles out of the single Strings
        double a = Double.parseDouble(values[0]);
        double b = Double.parseDouble(values[1]);

        // add them to an array
        double[] value = {a, b};

        // add the array to the array of arrays
        results[i] = value;
    }

    // then print the result
    for (double[] pair : results) {
        System.out.println(String.format("%.0f and %.2f", pair[0], pair[1]));
    }
}

是的,这些代码行很多,但很可能比 lambda 表达式更容易理解(在我看来,后者更酷、更优雅)。


推荐阅读