15,038,345 members
1.00/5 (1 vote)
See more:
I have a static class MyExtension,which has CountOf static function,this function must return number of that letters,which i wrote in string.In Main i must write like this`
```string str = "hello";
int r = str.CountOf('l');
Console.WriteLine(r);```

It will print 2, because there are two 'l' letter in string.

What I have tried:

i have tried like this`
```static public int CountOf(this string str,char ch)
{

return str.Count();
}```

but i know it's false,because it's return number of string
Posted
Updated 7-Feb-18 23:13pm
v2

## Solution 1

There are a lot of ways to do this, but the simplest is just to brute force it.
But ... this is your homework, so I'll give you no code!

1) Create a local interegr variable called `count` and set it to zero.
2) Use a `foreach` loop on the string to access each character
2.1) Inside the loop, check if the current character matches the "search for" character
2.1.1) If it matches, increment `count`
3) After the loop, return `count`
Suren97 8-Feb-18 6:21am

Thank you very much :)
OriginalGriff 8-Feb-18 6:24am

You're welcome!

## Solution 2

You have to go through the collection of chars, compare them to input and return the count of searched letter in a string.

C#
```string str = "hello";
char input = 'l';
int counter = 0;
//method 1
foreach(char a in str)
{
if(a==input) counter++;
}
//counter = 2

//method 2 - linq
var result = str.Count(x=>x==input);
//result = 2```
v2
Karthik_Mahalingam 8-Feb-18 5:59am

5
Maciej Los 8-Feb-18 6:22am

Thank you, Karthik
Suren97 8-Feb-18 6:22am

Thank you very much :)
Maciej Los 8-Feb-18 6:22am

You're very welcome.
Suren97 8-Feb-18 6:27am

i alredy accepted :)
Maciej Los 8-Feb-18 6:29am

Thank you ;)

## Solution 3

You could use LINQ count, see answers here: count the number of characters in a string[^]
Suren97 8-Feb-18 6:22am

Thank you very much :)