0

New to c#. I want my program to count the amount that a specific letter appears in a string.

public static int countLetters(string word, string countableLetter)
{
    int count = 0;
    foreach (char c in word)
    {
        count++;
    }
    return count;
}
Jazqa
  • 5
  • 1
  • 1
  • 5

2 Answers2

2

If you searching for exact character then change the second paramater type to char:

public static int countLetters(string word, char countableLetter)
{
    int count = 0;
    foreach (char c in word)
    {
        if(countableLetter == c)
           count++;
    }
    return count;
}

But you can do it with Count() method which included in System.Linq namespace:

return word.Count(x => x == countableLetter);

Additional:

If you want to find any char which contains in any string, then you can use:

public static int countLetters(string word, string countableLetters)
{
    int count = 0;
    foreach (char c in word)
    {
        if(countableLetters.Contains(c))
           count++;
    }
    return count;
}

or with LINQ:

return word.Count(x => countableLetters.Contains(x));
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
1

You can use Enumerable.Count for that:

var count = word.Count(ch => ch == countableLetter);

Note you should change countableLetter to a char instead of a string.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321