c# - find the second highest frequency of the character in the string -
i want find second highest frequency of character in string. example: abccddd
o/p should : c
i tried dictionary. storing in dictionary. moreover, sorting it. dont know how should proceed.
string input = tb_input.text; dictionary<string, int> di = new dictionary<string, int>(); (int = 0; < 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 storing number of occurrences in items
. should store character well:
var items = di.orderbydescending(x => x.value).tolist(); return items[1].key;
also, why start 0
? should add 1
dictionary, when it's not there:
else { di.add(input[i].tostring(), 1); }
update
just let know, can solved using linq:
return input.groupby(x => x).orderbydescending(x => x.count()).elementat(1).key;
Comments
Post a Comment