Created
January 12, 2025 06:03
-
-
Save huzpsb/83a098b3e4b481a4679332db31de728f to your computer and use it in GitHub Desktop.
CSV line spliter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
public class CSV { | |
public static String[] splitLine(String line) { | |
List<String> partsList = new ArrayList<>(); | |
char[] chars = line.toCharArray(); | |
boolean inQuotes = false; | |
StringBuilder currentPart = new StringBuilder(); | |
int idx = 0; | |
while (true) { | |
if (idx >= chars.length) { | |
partsList.add(currentPart.toString()); | |
break; | |
} | |
char c = chars[idx]; | |
if (c == ',' && !inQuotes) { | |
partsList.add(currentPart.toString()); | |
currentPart = new StringBuilder(); | |
} else if (c == '"') { | |
if (inQuotes) { | |
if (idx + 1 < chars.length && chars[idx + 1] == '"') { | |
currentPart.append('"'); | |
idx++; | |
} else { | |
inQuotes = false; | |
} | |
} else { | |
inQuotes = true; | |
} | |
} else { | |
currentPart.append(c); | |
} | |
idx++; | |
} | |
return partsList.toArray(new String[0]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment