要查找字符串中每个单词的频率,您可以尝试运行以下代码-
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 = "Football!"; 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 l Occurrence = 2 times Character o Occurrence = 2 times
上面,我们设置了一个字符串和一个整数数组。这有助于我们获得重复的值。该方法计算-
static void calculate(String s, int[] cal) { for (int i = 0; i < s.Length; i++) cal[s[i]]++; }
然后打印该值,该值也显示重复的元素-
for (int i = 0; i < maxCHARS; i++) if(cal[i] > 1) { Console.WriteLine("Character "+(char)i); Console.WriteLine("Occurrence = " + cal[i] + " times"); }