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");