如何使用C#获取字符串中出现频率最高的字符?
字符串中出现频率最高的字符是指出现次数最多的字符。可以使用以下示例进行演示。
String: apples are red The highest occurring character in the above string is e as it occurs 3 times, which is more than the occurrence of any other character.
下面是一个使用C#获取字符串中出现频率最高的字符的程序。
示例
using System; namespace charCountDemo { public class Example { public static void Main() { String str = "abracadabra"; int []charCount = new int[256]; int length = str.Length; for (int i = 0; i < length; i++) { charCount[str[i]]++; } int maxCount = -1; char character = ' '; for (int i = 0; i < length; i++) { if (maxCount < charCount[str[i]]) { maxCount = charCount[str[i]]; character = str[i]; } } Console.WriteLine("The string is: " + str); Console.WriteLine("The highest occurring character in the above string is: " + character); Console.WriteLine("Number of times this character occurs: " + maxCount); } } }
输出
上述程序的输出如下所示。
The string is: abracadabra The highest occurring character in the above string is: a Number of times this character occurs: 5
现在,让我们来理解一下上述程序。
字符串str是abracadabra。创建一个名为charCount的新数组,大小为256,显示ASCII表中的所有字符。然后使用for循环遍历字符串str,并根据字符串中的字符递增charCount中的值。这可以在下面的代码片段中看到。
String str = "abracadabra"; int []charCount = new int[256]; int length = str.Length; for (int i = 0; i < length; i++) { charCount[str[i]]++; }
整数maxCount存储最大计数,character是出现次数最多的字符值。可以使用for循环确定maxCount和character的值。这可以在下面的代码片段中看到。
int maxCount = -1; char character = ' '; for (int i = 0; i < length; i++) { if (maxCount < charCount[str[i]]) { maxCount = charCount[str[i]]; character = str[i]; } }
最后,显示str、maxCount和character的值。这可以在下面的代码片段中看到。
Console.WriteLine("The string is: " + str); Console.WriteLine("The highest occurring character in the above string is: " + character); Console.WriteLine("Number of times this character occurs: " + maxCount);
广告