find the kth index of a substring in a string in csharp

To find the kth index of a substring in a string in C#, you can use the IndexOf method, along with the Substring method. Here's an example:

main.cs
string str = "hello world";
string substr = "world";
int k = 0; // kth occurrence of substring

int index = -1; // initialize index to -1 in case substring is not found
for (int i = 0; i <= k; i++)
{
    index = str.IndexOf(substr, index + 1);
    if (index == -1)
    {
        break; // exit loop if substring is not found
    }
}

if (index != -1)
{
    Console.WriteLine($"The kth index of {substr} in {str} is {index}");
}
else
{
    Console.WriteLine($"{substr} was not found in {str}");
}
496 chars
23 lines

This code loops through the string, calling IndexOf each time to find the next occurrence of the substring. The loop runs k+1 times to find the kth occurrence. Finally, the index of the kth occurrence is outputted, or a message is outputted if the substring was not found.

gistlibby LogSnag