I want to find the second highest frequency of the character in the string. For example: abccddd
O/p should be : c
I tried with dictionary. I am storing everything in dictionary. Moreover, I am also sorting it. Now I dont know how should I proceed.
string input = tb_input.Text;
Dictionary<string, int> di = new Dictionary<string, int>();
for (int i = 0; i < input.Length; i++)
{
if (di.ContainsKey(input[i].ToString()))
{
int value = di[input[i].ToString()];
value++;
di[input[i].ToString()] = value;
}
else
{
di.Add(input[i].ToString(), 0);
}
}
var items = di.Values.ToList();
items.OrderByDescending(x => x).ToList();
You're only storing number of occurrences in items
. You should store character as well:
var items = di.OrderByDescending(x => x.Value).ToList();
return items[1].Key;
Also, why do you start with 0
? You should probably add 1
to dictionary, when it's not already there:
else
{
di.Add(input[i].ToString(), 1);
}
Update
Just to let you know, it can be easily solved using LINQ:
return input.GroupBy(x => x).OrderByDescending(x => x.Count()).ElementAt(1).Key;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.