获取字符串中出现次数最多的字符的 C# 程序
要获取字符串中出现次数最多的字符,遍历给定字符串的长度并查找出现次数。
有了这个,设置一个新数组进行计算 −
for (int i = 0; i < s.Length; i++) a[s[i]]++; }
我们上面使用过的值 −
String s = "livelife!"; int[] a = new int[maxCHARS];
现在显示字符和出现次数 −
for (int i = 0; i < maxCHARS; i++) if (a[i] > 1) { Console.WriteLine("Character " + (char) i); Console.WriteLine("Occurrence = " + a[i] + " times"); }
我们来看看完整的代码 −
示例
using System; class Program { static int maxCHARS = 256; static void display(String s, int[] a) { for (int i = 0; i < s.Length; i++) a[s[i]]++; } public static void Main() { String s = "livelife!"; int[] a = new int[maxCHARS]; display(s, a); for (int i = 0; i < maxCHARS; i++) if (a[i] > 1) { Console.WriteLine("Character " + (char) i); Console.WriteLine("Occurrence = " + a[i] + " times"); } } }
输出
Character e Occurrence = 2 times Character i Occurrence = 2 times Character l Occurrence = 2 times
广告