将字符串值转换为double类型的2d数组
我有一个字符串:
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数组:
String[] array = stringProfileFormatted.split("(?<!\\G\\d+),");
因此,对于Array中的每个元素,每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表达式更容易理解(在我看来,它更酷,更优雅)。
这样的事情怎么样:
Arrays.stream("0,4.28 10,4.93 20,3.75".split(" ")) //Stream .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
如果你用“”分割得到一个维度的数组,那么你可以再次拆分并获得你想要的多维数组:
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