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