java - 将字符串值转换为 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 个逗号值的字符串。
不知道如何转换为二维数组。这甚至是正确的方法吗?
解决方案
我会一步一步地解决这个任务。
首先,我会String
用空格分割原始数据,然后用逗号分割结果,然后double
用Double.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 表达式更容易理解(在我看来,后者更酷、更优雅)。
推荐阅读
- c# - 如何使用单个 ajax 调用填充多个下拉列表
- openssl - 证书中的“-----BEGIN TRUSTED CERTIFICATE-----”是什么意思?
- python - 为什么我调用函数后全局变量没有更新?
- python - 如何将这段数据写入 csv 文件?
- python - 如何用python打开可执行文件
- php - 如何为多个按钮分配ajax变量
- javafx - 如何在宽度/高度发生变化时保持非托管节点位置固定
- javascript - 有没有办法跳过当前播放的视频(通过按键)并继续下一个视频?
- javascript - 使用 datetimepicker 的 chartjs 条形图过滤器
- sql - 如何显示最近 3 个月的字段日期(数据日期类型)