Count occurrences of a character within a string in C#
This post will discuss how to count occurrences of a given character in a string in C#.
1. Using Enumerable.Count()
method (System.Linq
)
The recommended solution is to use LINQ’s Count() method to count occurrences of the given character in a string. This method is demonstrated below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; public class Example { public static void Main() { string str = "Techie Delight"; char ch = 'e'; int freq = str.Count(f => (f == ch)); Console.WriteLine(freq); } } /* Output: 3 */ |
2. Using Enumerable.Where()
method (System.Linq
)
Here’s another LINQ solution that uses the Where() method to filter the string. The following code example shows how to use this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; public class Example { public static void Main() { string str = "Techie Delight"; char ch = 'e'; int freq = str.Where(x => (x == ch)).Count(); Console.WriteLine(freq); } } /* Output: 3 */ |
3. Using String.Split()
method
Here, the idea is to split the string with a specified character using the String.Split() method and use the Length
property of the resultant string array to determine the count. This is demonstrated below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { string str = "Techie Delight"; char ch = 'e'; int freq = str.Split(ch).Length - 1; Console.WriteLine(freq); } } /* Output: 3 */ |
4. Using foreach
loop
We can also write our own logic for this simple task. The idea is to iterate over the characters in the string using a foreach loop and keep a matching character count.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; public class Example { public static void Main() { string str = "Techie Delight"; char ch = 'e'; int freq = 0; foreach (char c in str) { if (c == ch) { freq++; } } Console.WriteLine(freq); } } /* Output: 3 */ |
5. Using Regex.Matches()
method
Regex.Matches() method is used to search for the specified input string for all occurrences of the specified regular expression. We can use it as follows to count occurrences of a character within a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string str = "Techie Delight"; char ch = 'e'; int freq = Regex.Matches(str, ch.ToString()).Count; Console.WriteLine(freq); } } /* Output: 3 */ |
That’s all about counting occurrences of a character within a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)