C#统计给定的文本中字符出现的次数,使用循环和递归两种方法
1、使用循环:
/// <summary> /// 使用For循环统计文本字符串中某一字符出现的次数 /// </summary> /// <param name="c">指定字符</param> /// <param name="text">文本字符串</param> /// <returns></returns> public int CalauteCharShowCount_For(char c,string text) { int count=0; //定义一个计数器 //循环统计 for (int i = 0; i < text.Length; i++) { if (text[i] == c) count++; } return count; }
2、使用递归:
/// <summary> /// 使用递归统计文本中某一字符出现的次数 /// </summary> /// <param name="str">文本字符串</param> /// <param name="c">指定字符</param> /// <returns></returns> public int CaluateCharShowCount_Recursion(string str,char c) { if (str.Length == 0) return 0; if (str.Length == 1) { if (str == c.ToString()) return 1; else return 0; } if (str.Length == 2) return CaluateCharShowCount_Recursion(str.Substring(0, 1), c) + CaluateCharShowCount_Recursion(str.Substring(1, 1), c); else return CaluateCharShowCount_Recursion(str.Substring(0, 1), c) + CaluateCharShowCount_Recursion(str.Substring(1), c); }
//调用方法: int count_for= CalauteCharShowCount('A',"AbcSjHSHABNJKL"); int count_recursion=CaluateCharShowCount("AbcSjHSHABNJKL",'A');
浙公网安备 33010602011771号