C#程序查找最频繁的元素
假设我们的字符串是-
String s = "HeathLedger!";
现在创建一个新数组。
int []cal = new int[maxCHARS];
创建一个新方法,并在其中传递字符串和新数组。查找一个字符的最大出现次数。
static void calculate(String s, int[] cal) {
for (int i = 0; i < s.Length; i++)
cal[s[i]]++;
}让我们看完整的代码-
示例
using System;
class Demo {
static int maxCHARS = 256;
static void calculate(String s, int[] cal) {
for (int i = 0; i < s.Length; i++)
cal[s[i]]++;
}
public static void Main() {
String s = "thisisit!";
int []cal = new int[maxCHARS];
calculate(s, cal);
for (int i = 0; i < maxCHARS; i++)
if(cal[i] > 1) {
Console.WriteLine("Character "+(char)i);
Console.WriteLine("Occurrence = " + cal[i] + " times");
}
}
}输出结果
Character i Occurrence = 3 times Character s Occurrence = 2 times Character t Occurrence = 2 times
热门推荐
10 朋友药店开业祝福语简短
11 女性生日祝福语简短优美
12 新年祝福语长辈简短红包
13 七一祝福语明信片文案简短
14 新年祝福语独创文字简短
15 舰长生日祝福语简短
16 最美的留言祝福语简短
17 周岁宴舅舅祝福语简短
18 员工对同事祝福语简短