将字符串值转换为双精度类型的二维数组



我有一个字符串:

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

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

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

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

首先,我将原始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 表达式更容易理解(在我看来,lambda 表达式更酷、更优雅(。

像这样的事情呢:

Arrays.stream("0,4.28 10,4.93 20,3.75".split(" ")) //Stream<String>
.map(s -> 
Arrays.stream(s.split(",")) // take an individual string like 0,4.28  
.map(Double::parseDouble) // and transform it to a double array
.toArray(Double[]::new)
)
.toArray(Double[][]::new);

结果是

$8 ==> Double[3][] { 
Double[2] { 0.0, 4.28 }, 
Double[2] { 10.0, 4.93 }, 
Double[2] { 20.0, 3.75 } 
}

如果你的字符串遵循你描述的模式,那么你这样做是这样的:

String stringProfile = "0,4.28 10,4.93 20,3.75";
String[] split = stringProfile.split(" "); // split by space;
double[][] a = new double[split.length][]; // your result
for(int i = 0; i < split.length; i++) {
String[] numbers = split[i].split(","); // split by ,
double[] doubles = Arrays.stream(numbers).mapToDouble(Double::new).toArray(); //create 1-D array
a[i] = doubles; // assign it do your result
}

假设字符串严格遵循给定的示例模式,则可以使用以下代码:

String stringProfile = "0,4.28 10,4.93 20,3.75";
stringProfile = stringProfile.replace(' ', ',');
String [] strArry = stringProfile.split(",");
double [][] doubleArray = new double [strArry.length/2][2];
for(int i=0, j=0; i<strArry.length; i=i+2, j++) {
doubleArray [j][0] = Double.valueOf(strArry[i]);
doubleArray [j][1] = Double.valueOf(strArry[i+1]);
}

如果你用"拆分,你会得到一个一维的数组,那么你可以再次拆分并得到一个你想要的多维数组:

String arrayS = "0,4.28 10,4.93 20,3.75";
String [] a = arrayS.spit(" ");
double [][] arrayD;
for(String j: a){
arrayD.append(j.split(","));
}
//then print your array here

最新更新