How to count the number of occurrences of a character or substring in a string in C#?
Hello everyone! I'm a beginner C# developer and I've encountered a task that seems simple, but I can't find an elegant solution. I need to count how many times a specific character (e.g., 'a') appears in a string. I tried writing a loop manually, but it looks cumbersome. Here's my current code:
string text = "Hello, world! Hello, C#!";
char target = 'l';
int count = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == target)
count++;
}
Console.WriteLine(count); // Outputs 4
This works, but it seems to me that C# should have a built-in solution. Additionally, I need to count not only characters but also entire substrings. For example, how many times the word "Hello" appears in the string "HelloHelloWorld". If I use the same approach with a loo