2.3. Finding the Location of All Occurrences of a String Within Another String

Problem

You need to search a string for every occurrence of a specific string. In addition, the case sensitivity, or insensitivity, of the search needs to be controlled.

Solution

Using IndexOf or IndexOfAny in a loop, you can determine how many occurrences of a character or string exist as well as their locations within the string. To find each occurrence of a string in another string using a case-sensitive search, use the following code:

	using System;
	using System.Collections;
	using System.Collections.Generic;

	static class CharStrExtMethods
	{
	    public static int[] FindAll(this string matchStr, string searchedStr,
	                                int startPos)
	    {
	        int foundPos = -1; // -1 represents not found.
	            int count = 0;
	        List<int> foundItems = new List<int>();

	        do
	        {
	              foundPos = searchedStr.IndexOf(matchStr, startPos, StringComparison.
Ordinal);
	                  if (foundPos > -1)
	              {
	                  startPos = foundPos + 1;
	                  count++;
	                  foundItems.Add(foundPos);

	                      Console.WriteLine("Found item at position: " + foundPos.
ToString());
	              }
	          } while (foundPos > -1 && startPos < searchedStr.Length);

	          return ((int[])foundItems.ToArray());
	    }
	}

If the FindAll extension method is called with the following parameters:

	string data = "Red";
	int[] allOccurrences = data.FindAll("BlueTealRedredGreenRedYellow", 0);

the string "Red" is found at locations 8 and 19 in the string searchedStr. This code uses the IndexOf method inside a loop to iterate through each found matchStr string in the searchStr string. ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.