-
Oct 21st, 2015, 04:45 AM
#1
Count character Occurrences in a string
-
Jan 27th, 2021, 10:55 PM
#2
Member
Re: Count character Occurrences in a string
Hello, @karenInstructor
Please try this code, To Count character Occurrences in a string
Code:
using System;
public class GFG {
// Method that return count of the given
// character in the string
public static int count(string s, char c)
{
int res = 0;
for (int i = 0; i < s.Length; i++)
{
// checking character in string
if (s[i] == c)
res++;
}
return res;
}
// Driver method
public static void Main()
{
string str ="GoodMorning!";
char c = 'o';
Console.WriteLine(count(str, c));
}
}
I hope this code will be useful to you.
Thank you.
< advertising removed by moderator >
-
Jan 27th, 2021, 11:31 PM
#3
Re: Count character Occurrences in a string
Originally Posted by Sherin
I hope this code will be useful to you.
You can post whatever you want, wherever you want, as long as it is within site guidelines. That said:
1. This thread is over five years old. Posting to such old threads may help others who find it in future but it's not likely to help the OP.
2. This thread is in the CodeBank, so it is sharing working code rather than asking for help with a problem.
3. Your code doesn't do what the code in post #1 does. Your code will count the occurrences of a specific character only. The original code provides a count of each character in the text. To do that with your code, you'd first have to know which characters were in the text, or else you'd have to search for every single possible character and then discard the zero counts. You'd also have to search the entire text once for each character, making it much slower.
4. Your code isn't nearly the most succinct way to do what it actually does, which would be:
vb.net Code:
Console.WriteLine(str.Count(ch => ch == c));
No need for the dedicated method at all, as the existing Enumerable.Count method can already do effectively the same thing.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|