Find character with most occurrences in string?

前端 未结 10 998
一生所求
一生所求 2020-11-27 17:49

For example, I have a string:

\"abbbbccd\"

b has the most occurrences. When using C++, the easiest way to handle this is inser

相关标签:
10条回答
  • 2020-11-27 18:28

    Find the simplest and without built in function used

    sample code and links

    public char MostOccurringCharInString(string charString)
    {
    int mostOccurrence = -1;
    char mostOccurringChar = ' ';
    foreach (char currentChar  in charString)
    {
        int foundCharOccreence = 0;
        foreach (char charToBeMatch in charString)
        {
            if (currentChar == charToBeMatch)
                foundCharOccreence++;
        }
        if (mostOccurrence < foundCharOccreence)
        {
            mostOccurrence = foundCharOccreence;
            mostOccurringChar = currentChar;
        }
     }
      return mostOccurringChar;
    }
    

    Know more about how to get max occurrence and what is the flow.

    How to get max occurred character and max occurrence in string

    0 讨论(0)
  • 2020-11-27 18:30

    This because someone asked for a 2.0 version, so no LINQ.

    Dictionary<char, int> dict = new Dictionary<char, int>();
    
    int max = 0;
    
    foreach (char c in "abbbbccccd")
    {
        int i;
        dict.TryGetValue(c, out i);
        i++;
        if (i > max)
        {
            max = i;
        }
        dict[c] = i;
    }
    
    foreach (KeyValuePair<char, int> chars in dict)
    {
        if (chars.Value == max)
        {
            Console.WriteLine("{0}: {1}", chars.Key, chars.Value);
        }
    }
    

    Instead this for the LINQ version. It will extract paired "bests" (aaaabbbb == a, b). It WON'T work if str == String.Empty.

    var str = "abbbbccccd";
    
    var res = str.GroupBy(p => p).Select(p => new { Count = p.Count(), Char = p.Key }).GroupBy(p => p.Count, p => p.Char).OrderByDescending(p => p.Key).First();
    
    foreach (var r in res) {
        Console.WriteLine("{0}: {1}", res.Key, r);
    }
    
    0 讨论(0)
  • 2020-11-27 18:34
    string testString = "abbbbccd";
    var charGroups = (from c in testString
                        group c by c into g
                        select new
                        {
                            c = g.Key,
                            count = g.Count(),
                        }).OrderByDescending(c => c.count);
    foreach (var group in charGroups)
    {
        Console.WriteLine(group.c + ": " + group.count);
    }
    
    0 讨论(0)
  • 2020-11-27 18:34

    Inspired from Stephen's answer, almost the same:

    public static IEnumerable<T> Mode<T>(this IEnumerable<T> input)
    {
        var dict = input.ToLookup(x => x);
        if (dict.Count == 0)
            return Enumerable.Empty<T>();
        var maxCount = dict.Max(x => x.Count());
        return dict.Where(x => x.Count() == maxCount).Select(x => x.Key);
    }
    
    var modes = "".Mode().ToArray(); //returns { }
    var modes = "abc".Mode().ToArray(); //returns { a, b, c }
    var modes = "aabc".Mode().ToArray(); //returns { a }
    var modes = "aabbc".Mode().ToArray(); //returns { a, b }
    

    Update: Did a quick benchmarking of this answer vs Jodrell's answer (release build, debugger detached, oh yes)

    source = "";

    iterations = 1000000

    result:

    this - 280 ms
    Jodrell's - 900 ms
    

    source = "aabc";

    iterations = 1000000

    result:

    this - 1800 ms
    Jodrell's - 3200 ms
    

    source = fairly large string - 3500+ char

    iterations = 10000

    result:

    this - 3200 ms
    Jodrell's - 3000 ms
    
    0 讨论(0)
  • 2020-11-27 18:35
            //find most occuring character and count from below string
    
            string totest = "abcda12Zernn111y";
    
            string maxOccuringCharacter = "";
            int maxOccurence = 0;string currentLoopCharacter = ""; string updatedStringToTest = "";int cnt = 0;
    
            for (int i = 0; i < totest.Length; i++)
            {
                currentLoopCharacter = totest[i].ToString();
                updatedStringToTest = totest.Replace(currentLoopCharacter, "");
    
                cnt = totest.Length - updatedStringToTest.Length;
    
                if (cnt > maxOccurence)
                {
                    maxOccuringCharacter = currentLoopCharacter;
                    maxOccurence = cnt;
                }
    
                totest = updatedStringToTest;
            }
    
            Console.WriteLine("The most occuring character is {0} and occurence was {1}", maxOccuringCharacter, maxOccurence.ToString());
            Console.ReadLine();
    
    0 讨论(0)
  • 2020-11-27 18:44
    #simplified expression using LINQ#
    string text = "abccdeeef";
    int length = text.ToCharArray().GroupBy(x => x).OrderByDescending(x => 
    x.Count()).First().Count();
    
    0 讨论(0)
提交回复
热议问题