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:
  1. List<string> Split(string source, char sep, char quote)
  2.         {
  3.             List<string> _cols = new List<string>();
  4.             int x = 0;
  5.             char s = '\0';
  6.             string sLine = "";
  7.             string src = source;
  8.             bool InQuote = false;
  9.  
  10.             //Append sep
  11.             if (src[src.Length - 1] != sep)
  12.             {
  13.                 src += sep;
  14.             }
  15.  
  16.             while (x < src.Length)
  17.             {
  18.                 //Check for quotes
  19.                 if (src[x] == quote)
  20.                 {
  21.                     InQuote = !InQuote;
  22.                 }
  23.                 //if char is not seperator and not in quotes add string to list.
  24.                 else if ((src[x] == sep) && (!InQuote))
  25.                 {
  26.                     //Add to collection.
  27.                     _cols.Add(sLine);
  28.                     //Clear the line.
  29.                     sLine = string.Empty;
  30.                 }
  31.                 else
  32.                 {
  33.                     //Prepare string for adding to list.
  34.                     sLine += source[x];
  35.                 }
  36.                 //INC Counter.
  37.                 x++;
  38.             }
  39.             //Return list.
  40.             return _cols;
  41.         }
  42.  
  43.         private void button1_Click(object sender, EventArgs e)
  44.         {
  45.             //No quote string
  46.             string Test1 = "one,two,six";
  47.             string Test2 = "'one,two,six',Test with quotes,'10,20'";
  48.  
  49.             List<string> lst = new List<string>();
  50.  
  51.             lst = Split(Test1, ',', '\'');
  52.  
  53.             MessageBox.Show("Test 1");
  54.  
  55.             foreach (string item in lst)
  56.             {
  57.                 MessageBox.Show(item);
  58.             }
  59.  
  60.             //Test 2
  61.             lst = Split(Test2, ',', '\'');
  62.  
  63.             MessageBox.Show("Test 2");
  64.  
  65.             foreach (string item in lst)
  66.             {
  67.                 MessageBox.Show(item);
  68.             }
  69.  
  70.             lst.Clear();
  71.         }