C#程序查找字符串中字符出现的次数
假设我们的字符串是-
String s = "mynameistomhanks";
现在创建一个新数组,并使用上面声明的字符串将其传递给新方法。这将计算字符串中字符的出现。
static void calculate(String s, int[] cal) { for (int i = 0; i < s.Length; i++) cal[s[i]]++; }
让我们看完整的代码。
示例
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 = "mynameistomhanks"; 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"); } if (cal[i] == 1) { Console.WriteLine("Character " + (char) i); Console.WriteLine("Occurrence = " + cal[i] + " time"); } } } }
输出结果
Character a Occurrence = 2 times Character e Occurrence = 1 time Character h Occurrence = 1 time Character i Occurrence = 1 time Character k Occurrence = 1 time Character m Occurrence = 3 times Character n Occurrence = 2 times Character o Occurrence = 1 time Character s Occurrence = 2 times Character t Occurrence = 1 time Character y Occurrence = 1 time