C# Count Substring in String

When programming in Visual Studio with C# (C-Shap), it can happen that you have to determine how often a substring occurs in another string.  With the number you can then make further processing and comparisons in the program.

The easiest way to determine the frequency of occurrence of a string in another string is to use a regex function. The corresponding code then looks as follows.

int cnt = Regex.Matches(myText, "MySearchText").Count

In this case the variable “myText” is the string which should be searched. And the variable “MySearchString” is the substring whose number is to be determined in “myText“.

The function Regex.Matches returns a MatchCollection, which contains all found values. The exact number can now be determined via the Count property of this collection and assigned to an integer variable for further processing, for example.

But you can also use the expression directly in an if-condition, for example, if you want to determine whether the search value/substring occurs in a certain number, in order to then execute any other statement, such as for binding some properties or similar.

if(Regex.Matches(myText, "MySearchText").Count > 2)
{
    //do something
}

Thus, it is possible to determine in a very clear way with only one line of code how often a certain text, character, letter or character string occurs in another text.

Leave a Reply

Your email address will not be published. Required fields are marked *