Created
May 11, 2015 19:04
-
-
Save bradjolicoeur/792ed78a74d88c251ddc to your computer and use it in GitHub Desktop.
Function for splitting a delimited and qualified string (CSV)
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
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