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

To find the kth index of a character in a string in C#, you can use the String.IndexOf() method.

This method takes the character you want to find as a parameter and returns the index of its first occurrence in the string. You can also pass a second parameter to specify the starting index for the search.

Here is an example code snippet that finds the 3rd occurrence of the letter 'a' in a string:

main.cs
string str = "banana";
int k = 3;
int index = -1;
int count = 0;
for (int i = 0; i < str.Length; i++)
{
    if (str[i] == 'a')
    {
        count++;
        if (count == k)
        {
            index = i;
            break;
        }
    }
}
Console.WriteLine("The {0}th occurrence of {1} is at index {2}", k, 'a', index);
325 chars
18 lines

In this example, we initialize a counter variable called count to keep track of the number of occurrences of the letter 'a' that we have found so far. We iterate over the characters in the string using a for loop, and for each 'a' that we find, we increment the count. If the count reaches the desired k value, we record the index of the character and break out of the loop. If we reach the end of the loop without finding the kth occurrence, we return -1 to indicate that the character was not found.

gistlibby LogSnag