在 C# 中找出字符串中每个单词的出现频率
要找到字符串中每个单词的出现频率,可以尝试运行以下代码 −
示例
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"); }
广告