Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn string values into 2d array of type double

I have a string:

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

I am trying to turn it into an array like as follows:

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

I've formatted the string to remove any whitespace and replace with a comma:

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

So now String stringProfileFormatted = "0,4.28,10,4.93,20,3.75";

I then create a String array:

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

So for every element in the Array is every 2 commas worth of string.

Not sure how to then convert into a 2d array. Is this even the right way to go about it?

like image 957
arsenal88 Avatar asked Dec 11 '22 05:12

arsenal88


2 Answers

I would go step by step resolving this task.

First, I would split the original String by a space, then split the results by comma each and afterwards create an array of double out of those values with 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]));
    }
}

Yes, these are a lot of lines of code, but most likely more easily understandable than lambda expressions (which are cooler and more elegant in my opinion).

like image 66
deHaar Avatar answered Dec 12 '22 19:12

deHaar


What about something like this:

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);

the result is

$8 ==> Double[3][] { 
        Double[2] { 0.0, 4.28 }, 
        Double[2] { 10.0, 4.93 }, 
        Double[2] { 20.0, 3.75 } 
}
like image 21
Anton Balaniuc Avatar answered Dec 12 '22 19:12

Anton Balaniuc