Finding the location of all occurrences of a string within another string

Problem:

This content is for a beginner programmer.

You need to search a string for ever occurrence of a specific string. In addition, the case sensitivity, or in sensitivity, of the search needs to be contorlled.

Solution:

Using IndxOf of IndexOfArry in a loop, you can determine how many occurences of a charactor 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:

public static int[] FindAll(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);
        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 mehtod is called with the following parameters:

  int[] allOccurrences = FindAll("Red", "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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s