0

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

1
  • 4
    Have you tried anything? What I would recommend is an embedded loop (outer gets the next line inner gets the fields from that line). I can give you the code but I want to know what you've tried so far. Commented Mar 12, 2012 at 19:19

2 Answers 2

2

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"]
Sign up to request clarification or add additional context in comments.

3 Comments

+1, however if the format in question is RFC 4180 type CSV, then only a proper parser will be able to parse it. For example, this is proper CSV with 3 columns: "abc,123","2345\n12","a,aa""b,bb""c,cc"
Fully agree @Max that only a proper parser can work with those kind of CSV data.
@Max: I have posted an update to my answer which should work with RFC 4180 type CSV as well.
1
    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(",");
    }

Comments

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.