How to find the second most frequent character in a string with C#

1 Answer

0 votes
using System;

public class Program
{
	public static char GetSecondMostFrequentChar(string s) {
		int[] count = new int[256]; // 256 = ASCII table size

		for (int i = 0; i < s.Length; i++) {
			count[s[i]]++;
		}

		int first = 0;
		int second = 0;

		for (int i = 0; i < 256; i++) {
			if (count[i] > count[first]) {
				second = first;
				first = i;
			}
			else if (count[i] > count[second] && count[i] != count[first]) {
			        second = i;
			    }
		}

		return (char)second;
	}

	public static void Main(string[] args)
	{
		string str = "bbaddddccce";

		Console.Write(GetSecondMostFrequentChar(str));
	}
}




/*
run:
   
c
   
*/

 



answered Aug 31, 2022 by avibootz
edited Aug 31, 2022 by avibootz

Related questions

...