Find location of all occurrences of string in other string

When we need to search a string for every occurrence of a specific string along with case consideration we can use the IndexOf or IndexOfAny in a loop. This helps to determine how many occurrences of a character or string exist as well as their locations within the string.

Example Code to find each occurrence of a string in another string using a case-sensitive search:

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( ));
}
}

Example of FindAll extension method called with the following parameters:

string data = "mad";
int[] allOccurrences = data.FindAll("Themadmanisinthemadhouse", 0);

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.