4

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?

3
  • Can you specify whether you mean multi-dimensional or 2-dimensional ? Your example is 2 dimensional, and my guess is you are interested in 2-dimentional arrays - Please correct to avoid confusion. Also are there any other helpful hints or assumptions that you can make ? Would the matrix be limited with a max dimension (would be reasonable to limit I think)? Commented Sep 13, 2018 at 14:15
  • Apologies, yes its a 2d array. Each array in the 2d Array would have fixed length of 2. It would be pairs as the example shows Commented Sep 13, 2018 at 14:18
  • If your string strictly follows the pattern shown in your input i.e. pair of two values comma separated and each such pair separated by space - then it is straightforward to solve this, just split the string by \\s+, then split each string in that splitted strings by "," then use Double.valueOf(string) to get double, create a new 1d array and insert it in your 2d array. Not sure if there is more complexity to this. Commented Sep 13, 2018 at 14:22

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would change print to System.out.println(String.format("%.0f and %.2f", pair[0], pair[1])); for better formatting. It prints unnecessary digits after decimal.
This 0 and 4.28 instead of 0.000000 and 4.280000
5

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 } 
}

1 Comment

was just waiting for someone to come up with a one-liner using streams. :)
2

If your string follows the pattern you described then you do it like this:

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
}

Comments

0

Assuming that your string strictly follows the given sample pattern, you can make use of the following code:

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

Comments

-1

if you split with " " you get an array of one dimension, then you can split again and get a multidimensional array like you want:

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

2 Comments

Are you sure there is a append on array ? Question is specific to Java.
yeah, im confused, instead use add or push, im not remember what its, im only use arralist on java xd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.