mino
mino

Reputation: 7288

Java - Splitting data into a 2D array

I have a String of data called purchaseData which is separated into into lines with "\n" and into fields with "," (in CSV format).

How could I make a 2D string array so that the array contains arrays with each of the fields in. So for String[i][j], i would be the line value (position of row) and j would be the position of the field within the selected array of data (the row).

Upvotes: 0

Views: 9650

Answers (2)

aviad
aviad

Reputation: 8278

    String str = "YOUR_VERY_LONG_STRING";
    String[] lines = str.split("\n");
    String[][] linesCsv = new String[lines.length][];

    for (int i=0; i<lines.length; i++) {
        linesCsv[i] = lines[i].split(",");
    }

Upvotes: 1

anubhava
anubhava

Reputation: 785481

You can use String#split to create 2D array like this:

String str = "a,b,c,d,e,f\ng,h,i,j,k,l\nm,n,o,p,q,r";
String[] arr = str.split("\n");
String[][] csv = new String[arr.length][];
for(int r=0; r<arr.length; r++)
    csv[r] = arr[r].split(",");

Update: Since Max commented (and I agree) that my original answer won't work with RFC 4180 type CSV here I am posting an update to parse those complex CSV data like in my example below:

String str =
  "m,n,o,\"p\nx\",q,r\n\"abc,123\",\"45,12\",\"a,aa\",\"b,bb\",\"c,cc\",\"fo\no,bar\"";

String[] arr = str.split("\n\\s*(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
String[][] csv = new String[arr.length][];
for(int r=0; r<arr.length; r++)
    csv[r] = arr[r].split(",\\s*(?=([^\"]*\"[^\"]*\")*[^\"]*$)");

Testing:

for(int r=0; r<csv.length; r++)
    System.out.println(Arrays.toString(csv[r]));

OUTPUT:

[m, n, o, "p
x", q, r]
["abc,123", "45,12", "a,aa", "b,bb", "c,cc", "fo
o,bar"]

Upvotes: 2

Related Questions