Given a string str, a character ch and a value N, the task is to find the index of Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists.
Input: str = “Geeks”, ch = ‘e’, N = 2
Input: str = “GFG”, ch = ‘e’, N = 2
- Traverse the string character by character.
- Check for each character if it matches with the given character.
- Increment the count by 1, if it matches with the given character.
- If the count becomes equal to N, return the latest found index
- If count does not matches with N after the traversal, return -1
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Program to count occurrence of a given character in a string
- Count occurrence of a given character in a string using Stream API in Java
- Minimize the length of string by removing occurrence of only one character
- Python | Replacing Nth occurrence of multiple characters in a String with the given character
- Generate two output strings depending upon occurrence of character in input string.
- Generate two output strings depending upon occurrence of character in input string in Python
- Find a string such that every character is lexicographically greater than its immediate next character
- Find indices of all occurrence of one string in other
- Find the character in first string that is present at minimum index in second string
- Queries to find the first non-repeating character in the sub-string of a string
- Queries to find the last non-repeating character in the sub-string of a given string
- Longest suffix such that occurrence of each character is less than N after deleting atmost K characters
- Find the last non repeating character in string
- Find last index of a character in a string
- Find the first repeated character in a string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.