Turn string values into 2d array of type double

前端 未结 5 885
失恋的感觉
失恋的感觉 2021-01-20 00:01

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:

d         


        
5条回答
  •  粉色の甜心
    2021-01-20 00:24

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

提交回复
热议问题