Click here to Skip to main content
15,038,345 members
Please Sign up or sign in to vote.
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

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
   
Comments
Suren97 8-Feb-18 6:21am
   
Thank you very much :)
OriginalGriff 8-Feb-18 6:24am
   
You're welcome!
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
Comments
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.
Please accpet my solution (green button) if it was helpful (to mark your question as answered).
Suren97 8-Feb-18 6:27am
   
i alredy accepted :)
Maciej Los 8-Feb-18 6:29am
   
Thank you ;)
You could use LINQ count, see answers here: count the number of characters in a string[^]
   
Comments
Suren97 8-Feb-18 6:22am
   
Thank you very much :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900