字符串中出现次数最多的字符是出现次数最多的字符。可以使用以下示例演示这一点。
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存储最大计数,字符是出现最大次数的char值。可以使用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);