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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Python | Replacing Nth occurrence of multiple characters in a String with the given character
- 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
- Remove the first and last occurrence of a given Character from a String
- 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
- Minimize the length of string by removing occurrence of only one character
- Queries for Nth smallest character for a given range in a string
- Kth character from the Nth string obtained by the given operations
- Rearrange given string to maximize the occurrence of string t
- Longest suffix such that occurrence of each character is less than N after deleting atmost K characters
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Find a string such that every character is lexicographically greater than its immediate next character
- Nth character in Concatenated Decimal String
- Replace all occurrences of character X with character Y in given string
- Find indices of all occurrence of one string in other
- Find the occurrence of the given binary pattern in the binary representation of the array elements
- Replace every character of string by character whose ASCII value is K times more than it
- Replace every character of a string by a different character
- Map every character of one string to another such that all occurrences are mapped to the same character
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.