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

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

    As custom parser might be more suitable for this.

    This is something I wrote once when I had a specific (and very strange) parsing requirement that involved parenthesis and spaces, but it is generic enough that it should work with virtually any delimiter and text qualifier.

    public static IEnumerable ParseText(String line, Char delimiter, Char textQualifier)
    {
    
        if (line == null)
            yield break;
    
        else
        {
            Char prevChar = '\0';
            Char nextChar = '\0';
            Char currentChar = '\0';
    
            Boolean inString = false;
    
            StringBuilder token = new StringBuilder();
    
            for (int i = 0; i < line.Length; i++)
            {
                currentChar = line[i];
    
                if (i > 0)
                    prevChar = line[i - 1];
                else
                    prevChar = '\0';
    
                if (i + 1 < line.Length)
                    nextChar = line[i + 1];
                else
                    nextChar = '\0';
    
                if (currentChar == textQualifier && (prevChar == '\0' || prevChar == delimiter) && !inString)
                {
                    inString = true;
                    continue;
                }
    
                if (currentChar == textQualifier && (nextChar == '\0' || nextChar == delimiter) && inString)
                {
                    inString = false;
                    continue;
                }
    
                if (currentChar == delimiter && !inString)
                {
                    yield return token.ToString();
                    token = token.Remove(0, token.Length);
                    continue;
                }
    
                token = token.Append(currentChar);
    
            }
    
            yield return token.ToString();
    
        } 
    }
    

    The usage would be:

    var parsedText = ParseText(streamR, ' ', '"');
    

提交回复
热议问题