2013-10-11 43 views
1

我尝试在Stackflow中搜索以帮助我回答我的问题,但是我没有任何运气,因为我发现的主要是C++或Java。 我最近学会了递归,所以请原谅我的能力,不理解有关它的一些条款。创建递归方法来计算C中的特定字符

我的问题是,谁能回答我的代码中缺少的是什么?我需要我的代码才能成功计算我放入字符串的语句中的特定字符。现在我的代码只打印出声明。

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'); 
    } 
} 
+2

我不会建议在字符串递归计算字符,但老师不以为然? –

+2

@JeroenvanLangen我假设这是一个编程练习。 –

+3

那么,你不是在'Main'中调用'countCharacters'方法。另一件事是你需要传递paramcter'c'作为递归调用中的第二个参数 – Moho

回答

3

试试这个:

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); 
    } 
} 
+1

不,你修正了1个错误,但是'countCharacters'仍然不是不叫。 – David

+1

对不起,在批准建议编辑时,意外覆盖了您的修改。 –

+0

@David&Asad,tnx注意到 –