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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP