this.治疗完毕

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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');

 

posted on 2018-05-31 18:12  this.治疗完毕  阅读(1177)  评论(0)    收藏  举报