Hello.
Today I needed a way to split a string in to a list, but also skipping over commas resounded in quotes. so I looked at some old code I did for VB.NET, but found a bug, anyway looked into regex and came across some problems so gave up. then I started a new version from scratch. it's not in anyway full proof but it seems to serve my purpose. anyway I post here in the hope that it maybe us-full. if you find a bug and think you can fix it. please go ahead.
Code
csharp Code:
List<string> Split(string source, char sep, char quote) { List<string> _cols = new List<string>(); int x = 0; char s = '\0'; string sLine = ""; string src = source; bool InQuote = false; //Append sep if (src[src.Length - 1] != sep) { src += sep; } while (x < src.Length) { //Check for quotes if (src[x] == quote) { InQuote = !InQuote; } //if char is not seperator and not in quotes add string to list. else if ((src[x] == sep) && (!InQuote)) { //Add to collection. _cols.Add(sLine); //Clear the line. sLine = string.Empty; } else { //Prepare string for adding to list. sLine += source[x]; } //INC Counter. x++; } //Return list. return _cols; } private void button1_Click(object sender, EventArgs e) { //No quote string string Test1 = "one,two,six"; string Test2 = "'one,two,six',Test with quotes,'10,20'"; List<string> lst = new List<string>(); lst = Split(Test1, ',', '\''); MessageBox.Show("Test 1"); foreach (string item in lst) { MessageBox.Show(item); } //Test 2 lst = Split(Test2, ',', '\''); MessageBox.Show("Test 2"); foreach (string item in lst) { MessageBox.Show(item); } lst.Clear(); }


Reply With Quote
