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

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

To make things simple:

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


        
7条回答
  •  抹茶落季
    2020-11-30 00:50

    There's just a tiny problem with Squazz' answer.. it works for his string, but not if you add more items. E.g.

    string myString = "WordOne \"Word Two\" Three"
    

    In that case, the removal of the last quotation mark would get us 4 results, not three.

    That's easily fixed though.. just count the number of escape characters, and if it's uneven, strip the last (adapt as per your requirements..)

        public static List Split(this string myString, char separator, char escapeCharacter)
        {
            int nbEscapeCharactoers = myString.Count(c => c == escapeCharacter);
            if (nbEscapeCharactoers % 2 != 0) // uneven number of escape characters
            {
                int lastIndex = myString.LastIndexOf("" + escapeCharacter, StringComparison.Ordinal);
                myString = myString.Remove(lastIndex, 1); // remove the last escape character
            }
            var result = myString.Split(escapeCharacter)
                                 .Select((element, index) => index % 2 == 0  // If even index
                                                       ? element.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries)  // Split the item
                                                       : new string[] { element })  // Keep the entire item
                                 .SelectMany(element => element).ToList();
            return result;
        }
    

    I also turned it into an extension method and made separator and escape character configurable.

提交回复
热议问题