[英]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). 我有一个名为purchaseData
的数据字符串,该数据字符串分成带"\\n"
和带","
字段(CSV格式)。
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). 我如何制作一个2D字符串数组,以便该数组包含每个字段都在其中的数组。所以对于String[i][j]
, i
将是行值(行的位置),而j
将是行的位置所选数据数组(行)中的字段。
You can use String#split to create 2D array like this: 您可以使用String#split来创建2D数组,如下所示:
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: 更新:由于Max评论(并且我同意),我的原始答案不适用于RFC 4180 type CSV
,因此我发布了一个更新,以解析那些复杂的CSV数据,例如下面的示例:
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"]
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(",");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.