Skip to content

Instantly share code, notes, and snippets.

@bradjolicoeur
Created May 11, 2015 19:04
Show Gist options
  • Save bradjolicoeur/792ed78a74d88c251ddc to your computer and use it in GitHub Desktop.
Save bradjolicoeur/792ed78a74d88c251ddc to your computer and use it in GitHub Desktop.
Function for splitting a delimited and qualified string (CSV)
public string[] Split(string line, string qualifier, string delimiter)
{
bool qualifierState = false;
int startIndex = 0;
List values = new List();
//split the line into a character array so we can parse the line and take text qualifiers into consideration
char[] items = line.ToCharArray();
for (int charIndex = 0; charIndex <= items.Length-1; charIndex++)
{
if ((qualifier != null) && (items[charIndex].ToString() == qualifier))
{
//flip the state since we hit the next qualifier
qualifierState = !(qualifierState);
}
else if (!(qualifierState) & (items[charIndex].ToString() == delimiter))
{
//Grab the field and strip out any qualifiers
values.Add(line.Substring(startIndex, charIndex - startIndex).Replace(qualifier, string.Empty).Trim());
//Increment the start index
startIndex = charIndex + 1;
}
}
//If we are not at the end, then grab the last bit as the last field
if (startIndex <= line.Length)
values.Add(line.Substring(startIndex, line.Length - startIndex).Trim());
//return the string array
return values.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment