创建用于计算 C# 中特定字符的递归方法

本文关键字:字符 递归方法 用于 计算 创建 | 更新日期: 2023-09-27 18:34:55

我尝试在Stackflow中搜索以帮助我回答我的问题,但我没有任何运气,因为我找到的主要是C++或Java。我最近学习了递归,所以请原谅我不理解与它相关的一些术语的能力。

我对谁能够回答的问题是,我的代码中缺少什么?我需要我的代码来成功计算我放入字符串的语句中的特定字符。目前,我的代码只打印出语句。

public class CountCharacter
{
    public static void Main (string[] args)
    {
        string s = "most computer students like to play games";
        Console.WriteLine(s);
    }
    public static int countCharacters( string s, char c)
    {
        if (s.Length ==0)
            return 0;
        else if (s[0]==c)
            return 1+ countCharacters(s.Substring(1), 's');
        else
            return 0 + countCharacters (s.Substring(1),'s');
    }
}

创建用于计算 C# 中特定字符的递归方法

试试这个:

public class CountCharacter
{
    public static void Main (string[] args)
    {
        string s = "most computer students like to play games";
        Console.WriteLine(countCharacters(s, 's'));
    }
    public static int countCharacters( string s, char c)
    {
        if (s.Length == 0)
            return 0;
        else if (s[0] == c)
            return 1 + countCharacters(s.Substring(1), c);
        else
            return countCharacters(s.Substring(1), c);
    }
}
        static void Main(string[] args)
        {
            string s = " acv jk   ik  ";
            Console.WriteLine("Total space: {0}", CountSpace(s));
            Console.ReadLine();
        }
        private static int CountSpace(string s)
        {
            if (s.Length > 1)
                return s[0] == ' ' ? 1 + CountSpace(s.Substring(1, s.Length - 1)) : CountSpace(s.Substring(1, s.Length - 1));
            return s[0] == ' ' ? 1 : 0;
        }