C# 程序查找最常见元素
csharpprogrammingserver side programming更新于 2025/9/18 13:59:00
假设我们的字符串是 −
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

