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

前端 未结 6 1713
甜味超标
甜味超标 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:33

    Try with this it will work u c an split array string in many waysif you want to split by white space just put a space in (' ') .

      namespace LINQExperiment1
      {
      class Program
      {
      static void Main(string[] args)
      {
       string[] sentence = new string[] { "apple", "orange", "baboons  cows", " rainbow", "unicorns  gummy bears" };
    
      Console.WriteLine("option 1:"); Console.WriteLine("————-");
      // option 1: Select returns three string[]’s with
      // three strings in each.
      IEnumerable words1 =
      sentence.Select(w => w.Split(' '));
      // to get each word, we have to use two foreach loops
      foreach (string[] segment in words1)
      foreach (string word in segment)
      Console.WriteLine(word);
      Console.WriteLine();
      Console.WriteLine("option 2:"); Console.WriteLine("————-");
      // option 2: SelectMany returns nine strings
      // (sub-iterates the Select result)
      IEnumerable words2 =
      sentence.SelectMany(segment => segment.Split(','));
      // with SelectMany we have every string individually
      foreach (var word in words2)
      Console.WriteLine(word);
      // option 3: identical to Opt 2 above written using
      // the Query Expression syntax (multiple froms)
      IEnumerable words3 =from segment in sentence
      from word in segment.Split(' ')
      select word;
       }
      }
     }
    

提交回复
热议问题