在字符串结尾处删除系列的所有实例

时间:2012-07-30 16:06:22

标签: c# regex string trim

假设我们有一个返回字符数组定义的程序 - 所以我们可以将它复制粘贴到其他一些C#代码中。一个可能的结果是以下字符串:

// Current output:
return "CharArray = { {}, {123}, {}, {3 3}, {111}, {}, {}" + "};";

现在我们要消除CharArray的 end 处的额外空行,同时在开头或中间留下任何空行:

// Desired output:
"CharArray = { {}, {123}, {}, {3 3}, {111}" + "};";

(由于间距原因,数据之前或之间的任何空行都是必需的,但最后的空白空间对我们的代码没有任何意义。)

由于在操作之前不会添加最后一个括号和分号,因此最简单的方法是从字符串中删除“,{}”的所有尾随实例。我目前的解决方案是替换和修剪的非常开箱即用的组合...

// Red-Green solution:
return output.Replace(", {}", "!").TrimEnd('!').Replace("!", ", {}") + "};";

...这肯定会返回正确的结果,但是很长,让读者感到困惑,并且很可能在你第一次阅读时引起畏缩。

另外,我通常会使用的Regex.Replace只删除一个空行,(因为只有一行存在于字符串的末尾),而我宁愿不必通过循环来提供它:

// Sub-par solution: (birdie solution?)
 return Regex.Replace(testString, ", {}$", "") + "};";

如何从仅字符串的结尾中最好地删除系列字符的所有实例?我更喜欢一个既可读又不太慢或在机器上负担的结果。 (就用户目前所知,按下按钮后返回是即时的。)

3 个答案:

答案 0 :(得分:1)

你可以使用正则表达式:

return "\n" + Regex.Replace(testString, "(, {})+$", "") + "};";

这也将替换多次出现的搜索字符串

+运算符表示:前一个表达式的一个或多个出现

答案 1 :(得分:0)

试试这个:

    string TrimEndMultiple(string str, string end)
    {
        int lenend = end.Length;

        int start = str.Length - lenend;

        while (String.CompareOrdinal(str, start, end, 0, lenend) == 0)
        {
            start -= lenend;
        }

        // Addendum:
        return str.Substring(0, start + lenend);
    }

答案 2 :(得分:0)

我试了一下,TrimEndMultiple快了20倍:

    [MethodImplAttribute(MethodImplOptions.NoInlining)] 
    static string TrimEndMutiple(string str, string end)
    {
        int lenend = end.Length;

        int start = str.Length - lenend;

        while (String.CompareOrdinal(str, start, end, 0, lenend) == 0)
        {
            start -= lenend;
        }

        return str.Substring(0, start + lenend);
    } 

    static void Main(string[] args)
    {
        string s = "CharArray = { {}, {123}, {}, {3 3}, {111}, {}, {}";

        Regex reg = new Regex("(, {})+$", RegexOptions.Compiled);

        string s1 = reg.Replace(s, "");
        string s2 = TrimEndMutiple(s, ", {}");

        Stopwatch watch = new Stopwatch();

        int count = 1000 * 100;

        watch.Start();

        for (int i = 0; i < count; i++)
        {
            s1 = reg.Replace(s, "");
        }

        watch.Stop();

        Console.WriteLine("{0} {1,9:N3} ms", s1, watch.ElapsedTicks * 1000.0 / Stopwatch.Frequency);

        watch.Restart();

        for (int i = 0; i < count; i++)
        {
            s2 = TrimEndMutiple(s, ", {}"); 
        }

        watch.Stop();

        Console.WriteLine("{0} {1,9:N3} ms", s2, watch.ElapsedTicks * 1000.0 / Stopwatch.Frequency);
    }

结果:

CharArray = { {}, {123}, {}, {3 3}, {111}   298.014 ms
CharArray = { {}, {123}, {}, {3 3}, {111}    15.495 ms