在 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"); }
广告