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.

Comments

What did you think?

Used only for your avatar and replies; never published.