假设我们的字符串是-
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