Find character with most occurrences in string?

前端 未结 10 1060
一生所求
一生所求 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: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();
    

提交回复
热议问题