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
广告