Skip to content

Instantly share code, notes, and snippets.

@xebecnan
Created November 22, 2019 13:21
Show Gist options
  • Save xebecnan/c7a146b1d8d1257f8ffb4a0189aa8fef to your computer and use it in GitHub Desktop.
Save xebecnan/c7a146b1d8d1257f8ffb4a0189aa8fef to your computer and use it in GitHub Desktop.
public static class SimpleCSVParser {
static List<List<string>> ParseCSV(string text) {
var list = new List<List<string>>();
List<string> row = null;
var sb = new StringBuilder();
int i = 0;
while (i < text.Length) {
var c = text[i++];
if (c == '"') {
ReadString(text, ref i, sb);
} else if (c == '\r') {
continue;
} else if (c == '\n') {
AddCell(ref row, sb);
AddRow(list, ref row);
} else if (c == ',') {
AddCell(ref row, sb);
} else {
sb.Append(c);
}
}
AddCell(ref row, sb);
AddRow(list, ref row);
return list;
}
static void AddCell(ref List<string> row, StringBuilder sb) {
if (row == null) {
row = new List<string>();
}
row.Add(sb.ToString());
sb.Length = 0;
}
static void AddRow(List<List<string>> list, ref List<string> row) {
if (row != null) {
list.Add(row);
row = null;
}
}
static void ReadString(string text, ref int i, StringBuilder sb) {
while (i < text.Length) {
var c = text[i++];
if (c == '"') {
if (i >= text.Length) {
return;
}
c = text[i++];
if (c != '"') {
i--;
return;
}
}
sb.Append(c);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment