forked from lee2018jian/airbnb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseCSV
53 lines (48 loc) · 1.42 KB
/
parseCSV
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.List;
public class ParseCSV {
public static void main(String[] args) {
String input="John, Smith, [email protected], Los Angeles, 1\n" +
"Jane, Roberts, [email protected], \"San Francisco, CA\", 0 \n" +
"\"Alexandra \"\"Alex\"\"\", Menendez, [email protected], Miami, 1\n" +
"\"Alexandra Alex\"";
ParseCSV pcsv = new ParseCSV();
System.out.println(pcsv.parseCSV(input));
}
public String parseCSV(String str) {
List<String> res = new ArrayList<>();
boolean inQuote = false;
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < str.length() ; i++) {
if(inQuote) {
if(str.charAt(i)=='\"') {
if(i<str.length()-1&&str.charAt(i+1)=='\"') {
sb.append("\"");
i++;
}else {
inQuote= false;
}
}
else {
sb.append(str.charAt(i));
}
}else {
if(str.charAt(i)=='\"') {
inQuote=true;
}
else if(str.charAt(i)==',') {
res.add(sb.toString());
sb=new StringBuilder();
}
else {
sb.append(str.charAt(i));
}
}
}
if(sb.length()>0) {
res.add(sb.toString());
}
return String.join("|", res);
}
}