Find the number of string occurrences in another string

Sep 19, 2006

In C# 2.0 Microsoft introduces some new methods on the String class, one of them being Contains. The Contains method checks if a string in contained within another string in a case-sensitive way. It is very easy to use and a good addition to the String class. However, often you don’t want a case-sensitive search or you want to know how many times a particular string is contained within another. 

Because the String class doesn’t provide us with such methods, we have to create our own. Here are three methods – two overloaded – that does just that.

using System.Text.RegularExpressions;

 

/// <summary>

/// Checks if a string is contained within another.

/// The search is case-insensitive.

/// </summary>

/// <param name="text">The text to search.</param>

/// <param name="stringToFind">The string to look for.</param>

public static bool Contains(string text, string stringToFind)

{

  return NumberOfOccurrences(text, stringToFind) > 0;

}

 

/// <summary>

/// Searches the text for occurrences of a specific string.

/// The search is case-insensitive.

/// </summary>

/// <param name="text">The text to search.</param>

/// <param name="stringToFind">The string to look for.</param>

public static int NumberOfOccurrences(string text, string stringToFind)

{

  return NumberOfOccurrences(text, stringToFind, RegexOptions.IgnoreCase);

}

 

/// <summary>

/// Searches the text for occurrences of a specific string.

/// </summary>

/// <param name="text">The text to search.</param>

/// <param name="stringToFind">The string to look for.</param>

/// <param name="options">Specify the regex option.</param>

public static int NumberOfOccurrences(string text, string stringToFind, RegexOptions options)

{

  if (text == null || stringToFind == null)

  {

    return 0;

  }

 

  Regex reg = new Regex(stringToFind, options);

  return reg.Matches(text).Count;
}

Example of use

if (Contains("Hello world", "hello"))

{

  DoSomething();

}

 

if (NumberOfOccurrences("Hello world", "o") > 1)

{

  DoSomething();

}

 

if (NumberOfOccurrences("Hello world", "o", RegexOptions.None) = 2)

{

  DoSomething();
}

Let’s hope they add similar functionality to the .NET Framework in the future. To read more on regular expression, read this guide on MSDN.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (2) -

 josh
josh
9/18/2006 11:21:38 PM #

nifty

 shortcircuited
shortcircuited
9/20/2006 8:43:58 AM #

Now if only string was not sealed it would be nice to extend the string class in such ways!

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.