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

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

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

  1、使用循环:

 1  /// <summary>
 2         /// 使用For循环统计文本字符串中某一字符出现的次数
 3         /// </summary>
 4         /// <param name="c">指定字符</param>
 5         /// <param name="text">文本字符串</param>
 6         /// <returns></returns>
 7         public int CalauteCharShowCount_For(char c,string text)
 8         {   
 9             int count=0; //定义一个计数器 
10             //循环统计
11             for (int i = 0; i < text.Length; i++)
12             {
13                 if (text[i] == c)
14                     count++;
15             }
16             return count;
17         }


       2、使用递归:

 1  /// <summary>
 2         /// 使用递归统计文本中某一字符出现的次数
 3         /// </summary>
 4         /// <param name="str">文本字符串</param>
 5         /// <param name="c">指定字符</param>
 6         /// <returns></returns>
 7         public int CaluateCharShowCount_Recursion(string str,char c)
 8         {
 9             if (str.Length == 0)
10                 return 0;
11             if (str.Length == 1)
12             {
13                 if (str == c.ToString())
14                     return 1;
15                 else
16                     return 0;
17             }  
18             if (str.Length == 2)
19                 return CaluateCharShowCount_Recursion(str.Substring(0, 1), c) + CaluateCharShowCount_Recursion(str.Substring(1, 1), c);
20             else
21                 return CaluateCharShowCount_Recursion(str.Substring(0, 1), c) + CaluateCharShowCount_Recursion(str.Substring(1), c);          
22         }

调用方法:

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

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

原文地址:https://www.cnblogs.com/wangpf/p/net.html