Search code examples
c#stringloopsindexingindices

C# - Finding All Indices of a Substring


EDIT: So it turns out what I had before was correct, I was simply counting the indexes wrong. Thank you for your input though.

Working on a method that finds all substring indices in a given string from the user. I am having issues with getting correct positions from userString.IndexOf. I know it's finding all occurrences of the substring, but the integer index is off by a substantial amount.

private static void getSubStringPositions(string userString, string userSubString)
{
    string subStringPositions = "";
    int position = 0;

    if (userString.IndexOf(userSubString, position) == -1)
    {
        Console.WriteLine("Your sub-string was not found in your string.\n");
        return;
    }
    while (position < userString.Length)
    {
        position += userString.IndexOf(userSubString, position);
        subStringPositions += Convert.ToString(position) + ", ";
    }

    Console.WriteLine("The occurernce(s) for your sub-string are: " + subStringPositions + "\n\n");
    return;
}

I think it may be an issue with position += userString.IndexOf(userSubString, position); but am not entirely sure how I would go about setting the new start position while maintaing an accurate record of the substring locations.


Solution

  • Remove the += in front of position

       position = userString.IndexOf(userSubString, position);
    

    Also you should change your code to save the initial found position and set the position variable to search after the previous one

        // Initial check...
        position = userString.IndexOf(userSubString);
        if(position == -1)
        {
            Console.WriteLine("Your sub-string was not found in your string.\n");
            return;
        }
        // Save the found position and enter the loop
        subStringPositions = Convert.ToString(position) + ", ";
    
        while (position < userString.Length)
        {
            // Search restart from the character after the previous found substring
            position = userString.IndexOf(userSubString, position + 1);
            subStringPositions += Convert.ToString(position) + ", ";
        }
    

    As a final note, if this search produces many hits it is better to change the string concatenation using a StringBuilder class instance

        StringBuilder subStringPositions = new StringBuilder();
        subStringPositions.Append(Convert.ToString(position) + ", ");
    
        while (position < userString.Length)
        {
            // Search restart from the character after the previous found substring
            position = userString.IndexOf(userSubString, position + 1);
            subStringPositions.Append(Convert.ToString(position) + ", ";
        }
        Console.WriteLine("The occurrence(s) for your sub-string are: " + 
                          subStringPositions.ToString() + "\n\n");