删除多个不属于字符串文字的冗余空格

时间:2013-07-03 17:38:43

标签: c#

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

    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);

1 个答案:

答案 0 :(得分: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();
    }