Changing commas within quotes

Posted by user1822739 on Stack Overflow See other posts from Stack Overflow or by user1822739
Published on 2012-12-05T11:02:17Z Indexed on 2012/12/05 11:03 UTC
Read the original article Hit count: 124

Filed under:
|

I am trying to read the data in a text file which is separated by commas. My problem, is that one of my data pieces has a comma within it. An example of what the text file looks like is: a, b, "c, d", e, f. I want to be able to take the comma between c and d and change it to a semicolon so that I can still use the string.Split() method.

        using (StreamReader reader = new StreamReader("file.txt")) {
            string line;
            while ((line = reader.ReadLine ()) != null) {
                bool firstQuote = false;
                for (int i = 0; i < line.Length; i++) {
                    if (line [i] == '"' ) {
                        firstQuote = true;
                    }  
                    else if (firstQuote == true) {
                        if (line [i] == '"') {
                            break;
                        } 
                     if ((line [i] == ',')) {
                            line = line.Substring (0, i) + ";" + line.Substring (i + 1, (line.Length - 1) - i);
                        }
                    }

                }
                Console.WriteLine (line);
            }
        }

I am having a problem. Instead of producing a, b, "c; d", e, f, it is producing a, b, "c; d"; e; f. It is replacing all of the following commas with semicolons instead of just the comma in the quotes. Can anybody help me fix my existing code?

© Stack Overflow or respective owner

Related posts about c#

Related posts about split