TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# String Occurrence Count

This C# example program counts the occurrences of a string within another string. It uses IndexOf and a while-loop.

String occurrence count. A substring may occur several times in a string.

We can count the number of occurrences of one string in another string. This is useful for validity checks. It helps with checking that only one tag string is found in your HTML.

Input and output

Input strings: Sam's first name is Sam.
	       Dot Net Perls is about Dot Net
	       No duplicates here
	       aaaa
Words:         Sam                     
	       Net
	       here
	       aa
Counts:        2                       
	       2
	       1
	       2

Example. To start, here is an easy method that uses IndexOf and a loop to count up the number of occurrences of a specified string in another string. This method receives two string parameters.

Note: The first parameter is the string that contains the data you are checking. The second is the pattern you want to count.

C# program that counts strings

using System;

class Program
{
    static void Main()
    {
	string s1 = "Sam's first name is Sam.";
	string s2 = "Dot Net Perls is about Dot Net";
	string s3 = "No duplicates here";
	string s4 = "aaaa";

	Console.WriteLine(TextTool.CountStringOccurrences(s1, "Sam"));  // 2
	Console.WriteLine(TextTool.CountStringOccurrences(s1, "cool")); // 0
	Console.WriteLine(TextTool.CountStringOccurrences(s2, "Dot"));  // 2
	Console.WriteLine(TextTool.CountStringOccurrences(s2, "Net"));  // 2
	Console.WriteLine(TextTool.CountStringOccurrences(s3, "here")); // 1
	Console.WriteLine(TextTool.CountStringOccurrences(s3, " "));    // 2
	Console.WriteLine(TextTool.CountStringOccurrences(s4, "aa"));   // 2
    }
}

/// <summary>
/// Contains static text methods.
/// Put this in a separate class in your project.
/// </summary>
public static class TextTool
{
    /// <summary>
    /// Count occurrences of strings.
    /// </summary>
    public static int CountStringOccurrences(string text, string pattern)
    {
	// Loop through all instances of the string 'text'.
	int count = 0;
	int i = 0;
	while ((i = text.IndexOf(pattern, i)) != -1)
	{
	    i += pattern.Length;
	    count++;
	}
	return count;
    }
}

In this example, the counting method (CountStringOccurrences) is a static method. The method does not need to store state. We place it in a static class, a convenient place for helper methods.

Static Class

In the Main method, which we use to test the CountStringOccurrences method, we see that "Sam" occurs twice in the example string. This matches the requirement. It is usually best to simplify the branches in your code.

If

Also: It is not an extension method. But you are free to adapt it with the this-keyword.

Extension Method

Tip: You could count overlapping occurrences by changing the increment to "i++" instead of "i += pattern.Length".

String Length

An MSDN article shows how to count instances of a word with LINQ, but their approach is likely slow. It is confusing—I would not use it in an important program. The example mostly demonstrates the use of LINQ.

Count Occurrences: MSDN

Summary. We saw how to count occurrences of one, smaller string in another, larger string. Importantly, we only loop once over the source, which reduces the cost of the method. I use this method to do simple validation of HTML.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf