C#统计给定的文本中字符出现的次数,使用循环和递归两种方法

时间:2023-03-08 20:20:10

前几天看了一个.net程序员面试题目,题目是”统计给定的文本中字符出现的次数,使用循环和递归两种方法“。

  下面是我对这个题目的解法:

  1、使用循环:

  /// <summary>
/// 使用For循环统计文本字符串中某一字符出现的次数
/// </summary>
/// <param name="c">指定字符</param>
/// <param name="text">文本字符串</param>
/// <returns></returns>
public int CalauteCharShowCount_For(char c,string text)
{
int count=; //定义一个计数器
//循环统计
for (int i = ; 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 == )
return ;
if (str.Length == )
{
if (str == c.ToString())
return ;
else
return ;
}
if (str.Length == )
return CaluateCharShowCount_Recursion(str.Substring(, ), c) + CaluateCharShowCount_Recursion(str.Substring(, ), c);
else
return CaluateCharShowCount_Recursion(str.Substring(, ), c) + CaluateCharShowCount_Recursion(str.Substring(), c);
}

调用方法:

int count_for= CalauteCharShowCount('A',"AbcSjHSHABNJKL");

int count_recursion=CaluateCharShowCount("AbcSjHSHABNJKL",'A');