Skip to content

Instantly share code, notes, and snippets.

@huzpsb
Created January 12, 2025 06:03
Show Gist options
  • Save huzpsb/83a098b3e4b481a4679332db31de728f to your computer and use it in GitHub Desktop.
Save huzpsb/83a098b3e4b481a4679332db31de728f to your computer and use it in GitHub Desktop.
CSV line spliter
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