2013-10-11 42 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注意到 –