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
广告