Reputation: 15
I tried searching within Stackflow to help me answer my question but i did not have any luck since the ones i found are mainly in C++ or Java. I have recently learned Recursive so please pardon my ability to not understand some terms relating to it.
My question to who ever is able to answer is,what is missing in my code? I need my code to successfully count a specific character within a statement I put in a string. for now my code only prints out the statement.
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');
}
}
Upvotes: 1
Views: 3550
Reputation: 99
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;
}
Upvotes: 1
Reputation: 22083
Try this:
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);
}
}
Upvotes: 3