Count the Occurrences of String within another String in C#

Do you want to find the number of occurrences of a string within a string in C#? This article will explain how to do it.

How would you count occurrences of a string within a string (C#)?

For example, assume that the main string is “Abundantcode is a programming, soucrecode, technology related website”. If we need to find the number of occurrences of the comma (,) from the above string, below is a sample code snippet demonstrating how to get it.

using System;

using System.Collections.Generic;

using System.Data;

using System.IO;

using System.Linq;

namespace AbundantCode

{

internal class Program

{

// How to Count the Occurences of String within another String in C#

private static void Main(string[] args)

{

string MainString = "Abundantcode is a programming , sourcecode , technology related website";

int TotalStringOccurences = MainString.Count(f => f == ',');

Console.WriteLine(TotalStringOccurences);

Console.ReadKey();

}

}

}
Count the Occurrences of String within another String in C#