Split string by commas ignoring any punctuation marks (including ',') in quotation marks

前端 未结 6 1717
甜味超标
甜味超标 2021-01-22 06:10

How can I split string (from a textbox) by commas excluding those in double quotation marks (without getting rid of the quotation marks), along with other poss

6条回答
  •  滥情空心
    2021-01-22 06:45

    This was trickier than I thought, a good practical problem I think.

    Below is the solution I came up with for this. One thing I don't like about my solution is having to add double quotations back and the other one being names of the variables :p:

    internal class Program
    {
        private static void Main(string[] args)
        {
    
            string searchString =
                @"apple, orange, ""baboons, cows. dogs- hounds"", rainbow, ""unicorns, gummy bears"", abc, defghj";
    
            char delimeter = ',';
            char excludeSplittingWithin = '"';
    
            string[] splittedByExcludeSplittingWithin = searchString.Split(excludeSplittingWithin);
    
            List splittedSearchString = new List();
    
            for (int i = 0; i < splittedByExcludeSplittingWithin.Length; i++)
            {
                if (i == 0 || splittedByExcludeSplittingWithin[i].StartsWith(delimeter.ToString()))
                {
                    string[] splitttedByDelimeter = splittedByExcludeSplittingWithin[i].Split(delimeter);
                    for (int j = 0; j < splitttedByDelimeter.Length; j++)
                    {
                        splittedSearchString.Add(splitttedByDelimeter[j].Trim());
                    }
                }
                else
                {
                    splittedSearchString.Add(excludeSplittingWithin + splittedByExcludeSplittingWithin[i] +
                                             excludeSplittingWithin);
                }
            }
    
            foreach (string s in splittedSearchString)
            {
                if (s.Trim() != string.Empty)
                {
                    Console.WriteLine(s);
                }
            }
            Console.ReadKey();
        }
    }
    

提交回复
热议问题