Fastest way to implement Duplicate Character Removal in String (C#)

前端 未结 5 692
说谎
说谎 2020-12-14 12:43

In C#, what is the fastest way to detect duplicate characters in a String and remove them (removal including 1st instance of the duplicated character)?

5条回答
  •  醉话见心
    2020-12-14 12:55

    Here is a pretty fast one preserving order. But I'd be a little worried about how LINQ does Group and Where:

    string s = "nbHHkRvrXbvkn";
    Console.WriteLine( 
        s.ToCharArray()
            .GroupBy(c => c)
            .Where(g => g.Count() == 1)
            .Aggregate(new StringBuilder(), (b, g) => b.Append(g.Key)));
    

    Edit: This one beats Luke's in some cases still slower than dtb's, but it preserves the order

    private static string MyMethod(string s)
    {
        StringBuilder sb = new StringBuilder(s.Length);
        foreach (var g in s.ToCharArray().GroupBy(c => c))
            if (g.Count() == 1) sb.Append(g.Key);
    
        return sb.ToString();
    }
    

提交回复
热议问题