Split a string that has white spaces, unless they are enclosed within “quotes”?

后端 未结 7 732
无人共我
无人共我 2020-11-30 00:12

To make things simple:

string streamR = sr.ReadLine();  // sr.Readline results in:
                                 //                         one \"two two\         


        
7条回答
  •  感动是毒
    2020-11-30 01:09

    OP wanted to

    ... remove all spaces EXCEPT for the spaces found between quotation marks

    The solution from Cédric Bignon almost did this, but didn't take into account that there could be an uneven number of quotation marks. Starting out by checking for this, and then removing the excess ones, ensures that we only stop splitting if the element really is encapsulated by quotation marks.

    string myString = "WordOne \"Word Two";
    int placement = myString.LastIndexOf("\"", StringComparison.Ordinal);
    if (placement >= 0)
    myString = myString.Remove(placement, 1);
    
    var result = myString.Split('"')
                         .Select((element, index) => index % 2 == 0  // If even index
                                               ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)  // Split the item
                                               : new string[] { element })  // Keep the entire item
                         .SelectMany(element => element).ToList();
    
    Console.WriteLine(result[0]);
    Console.WriteLine(result[1]);
    Console.ReadKey();
    

    Credit for the logic goes to Cédric Bignon, I only added a safeguard.

提交回复
热议问题