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 婆婆高寿祝福语大全简短