0

How to split a string with a comma and don't split inside - "" with c# only.

For example this string "aa","b,b","asdds","sd,fd,sd,,f"

To this array/list - aa,b,b,asdds,sd,fd,sd,,f

Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36

2 Answers2

0
string s = "\"aa\",\"b,b\",\"asdds\",\"sd,fd,sd,,f\""; // The string (\" = ") when write it inside string 
List<string> s1 = new List<string>(); // List of the strings without the , and the "
string s2 = ""; // string for adding into the list
bool
  first = false, // If arrive to the first "
  second = false; // If arrive to the second "
foreach (char c in s) // Move over every char in the string
{
    if (second) // If reach the second
    {
        s1.Add(s2); // Add the string to the list
        s2 = ""; // Make s2 ready for new string
        first = false; // Make first be ready for another string
        second = false; // Make second be ready for another string
    }
    if (first) // If the string in the quotemark started
    {
        if (c == '"') // If the string in the quotemark ended
        {
            second = true; // Reach the second quotemark
        }
        else // If the string didn't end
        {
            s2 += c; // Add the char to the string
        }
    }
    if (c == '"' && !first && !second) // If the string just reach the first quotemark in a string 
    {
        first = true; // Reach the first quotemark
    }
}
if (second&&first) //For the last string that missed at the end
{
    s1.Add(s2); // Add the string to the list
}
Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36
0
string sample = "aa","b,b","asdds","sd,fd,sd,,f";
sample = sample.Replace("\",\", "&");
string[] targetA = sample.Split('&');