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

后端 未结 7 731
无人共我
无人共我 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:07

    You can use the TextFieldParser class that is part of the Microsoft.VisualBasic.FileIO namespace. (You'll need to add a reference to Microsoft.VisualBasic to your project.):

    string inputString = "This is \"a test\" of the parser.";
    
    using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(inputString)))
    {
        using (Microsoft.VisualBasic.FileIO.TextFieldParser tfp = new TextFieldParser(ms))
        {
            tfp.Delimiters = new string[] { " " };
            tfp.HasFieldsEnclosedInQuotes = true;
            string[] output = tfp.ReadFields();
    
            for (int i = 0; i < output.Length; i++)
            {
                Console.WriteLine("{0}:{1}", i, output[i]);
            }
        }
    }
    

    Which generates the output:

    0:This
    1:is
    2:a test
    3:of
    4:the
    5:parser.
    

提交回复
热议问题