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

To find the kth index of a character in a string in TypeScript, you can use the charAt() method and a loop to search for the character.

Here's an example function that takes a string and a number (k) and returns the index of the kth occurrence of the character "c" in the string:

index.ts
function findKthIndex(str: string, k: number, c: string): number {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str.charAt(i) === c) {
      count++;
      if (count === k) {
        return i;
      }
    }
  }
  return -1; // not found
}
260 chars
13 lines

This loop iterates over each character in the string, incrementing a count variable each time it finds the target character. When the count reaches the desired K value, the function returns the index of that character. If the character is not found, the function returns -1.

gistlibby LogSnag