Avatar ·

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 this task: I need to count how many times a specific character or substring appears inside a string. For example, I have the string "Hello World, Hello C#", and I want to find out how many times the letter 'l' or the word "Hello" appears in it. I tried using a for loop and iterating through each character, but it seems too cumbersome, especially if I need to search for a substring rather than a single character. I've also heard about the Split() method, but I'm not sure how to apply it correctly. Here's an example of my code that I wrote for counting characters, but it only works for a single character and seems suboptimal: ```csharp string text = "Hello World, Hello C#"; char target = 'l'; int count = 0; for (int i = 0; i < text.Length; i++) { if (tex