gpt4 book ai didi

java - 将字符串值转换为 double 类型的二维数组

转载 作者:搜寻专家 更新时间:2023-11-01 01:15:34 25 4
gpt4 key购买 nike

我有一个字符串:

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(" ", ",");

现在 String stringProfileFormatted = "0,4.28,10,4.93,20,3.75";

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

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

所以数组中的每个元素都是每 2 个逗号值的字符串。

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

最佳答案

我会逐步解决这个任务。

首先,我将原始的 String 用空格分开,然后用逗号分隔结果,然后使用 Double.parseDouble(String value) 从这些值中创建一个 double 数组。

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 表达式更容易理解(我认为后者更酷、更优雅)。

关于java - 将字符串值转换为 double 类型的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52315614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com