1

我试图找到一个函数来删除多余的连续空格,除非空格在字符串文字内,用单引号或双引号表示。

    string source   = "sqlcmd.exe    -Q \"LEAVE     SQL TEXT HERE   UNCHANGED BECAUSE IT'S IN A DBL QUOTE BLOCK\"";
    string expected = "sqlcmd.exe -Q \"LEAVE     SQL TEXT HERE   UNCHANGED BECAUSE IT'S IN A DBL QUOTE BLOCK\"";
    string actual = StringExtensions.RemoveRedundantSpaces(source);
    Assert.AreEqual(expected, actual);
4

1 回答 1

2

这是一种可能是最简单的蛮力方法(并且可以很容易地转换为扩展方法)。请注意,如果您的字符串引用不正确,这不一定会返回您所期望的(但会指出您正在解析的批处理文件中的问题)。

    private static void TrimRedundantSpaces(string input)
    {
        Console.WriteLine(input);

        StringBuilder output = new StringBuilder();
        char previousChar = '\0';
        bool inSingleQuote = false;
        bool inDoubleQuote = false;

        for (int i = 0; i < input.Length; i++)
        {
            switch (input[i])
            {
                case '\'':
                    if (! inDoubleQuote)
                        inSingleQuote = !inSingleQuote;
                    output.Append(input[i]);
                    break;

                case '"':
                    if (! inSingleQuote)
                        inDoubleQuote = !inDoubleQuote;
                    output.Append(input[i]);
                    break;

                case ' ':
                    if ((previousChar != ' ') || inSingleQuote || inDoubleQuote)
                        output.Append(' ');
                    break;

                default:
                    output.Append(input[i]);
                    break;
            }

            previousChar = input[i];
        }

        Console.WriteLine(output.ToString());
        Console.WriteLine();
    }

    [STAThread]
    static void Main(string[] args)
    {
        TrimRedundantSpaces("sqlcmd.exe    -Q 'LEAVE     SQL TEXT HERE   UNCHANGED BECAUSE IT'S IN A DBL QUOTE BLOCK'");
        TrimRedundantSpaces("sqlcmd.exe    -Q \"LEAVE     SQL TEXT HERE   UNCHANGED BECAUSE IT'S IN A DBL QUOTE BLOCK\"");
        TrimRedundantSpaces("sqlcmd.exe    -Q \"LEAVE     'SQL TEXT' HERE   UNCHANGED BECAUSE IT'S IN A DBL QUOTE BLOCK\"");
        Console.ReadLine();
    }
于 2013-07-03T18:17:42.327 回答