Find the Nth occurrence of a character in the given String
Last Updated :
22 Aug, 2023
Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists.
Examples:
Input: str = "Geeks", ch = 'e', N = 2
Output: 2
Input: str = "GFG", ch = 'e', N = 2
Output: -1
Approach:
- 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 the count does not match with N after the traversal, return -1
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// Nth occurrence of a character
#include <bits/stdc++.h>
using namespace std;
// Function to find the
// Nth occurrence of a character
int findNthOccur(string str,
char ch, int N)
{
int occur = 0;
// Loop to find the Nth
// occurrence of the character
for (int i = 0; i < str.length(); i++) {
if (str[i] == ch) {
occur += 1;
}
if (occur == N)
return i;
}
return -1;
}
// Driver Code
int main()
{
string str = "geeks";
char ch = 'e';
int N = 2;
cout << findNthOccur(str, ch, N);
}
Java
// Java implementation to find the
// Nth occurrence of a character
import java.util.*;
class GFG
{
// Function to find the
// Nth occurrence of a character
static int findNthOccur(String str,
char ch, int N)
{
int occur = 0;
// Loop to find the Nth
// occurrence of the character
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ch)
{
occur += 1;
}
if (occur == N)
return i;
}
return -1;
}
// Driver Code
public static void main(String[] args)
{
String str = "geeks";
char ch = 'e';
int N = 2;
System.out.print(findNthOccur(str, ch, N));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation to find the
# Nth occurrence of a character
# Function to find the
# Nth occurrence of a character
def findNthOccur(string , ch, N) :
occur = 0;
# Loop to find the Nth
# occurrence of the character
for i in range(len(string)) :
if (string[i] == ch) :
occur += 1;
if (occur == N) :
return i;
return -1;
# Driver Code
if __name__ == "__main__" :
string = "geeks";
ch = 'e';
N = 2;
print(findNthOccur(string, ch, N));
# This code is contributed by AnkitRai01
C#
// C# implementation to find the
// Nth occurrence of a character
using System;
class GFG
{
// Function to find the
// Nth occurrence of a character
static int findNthOccur(String str,
char ch, int N)
{
int occur = 0;
// Loop to find the Nth
// occurrence of the character
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ch)
{
occur += 1;
}
if (occur == N)
return i;
}
return -1;
}
// Driver Code
public static void Main(String[] args)
{
String str = "geeks";
char ch = 'e';
int N = 2;
Console.Write(findNthOccur(str, ch, N));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript implementation to find the
// Nth occurrence of a character.
// Function to find the
// Nth occurrence of a character
function findNthOccur(str, ch, N)
{
var occur = 0;
// Loop to find the Nth
// occurrence of the character
for (var i = 0; i < str.length; i++) {
if (str[i] == ch) {
occur += 1;
}
if (occur == N)
return i;
}
return -1;
}
var str = "geeks";
var ch = 'e';
var N = 2;
document.write( findNthOccur(str, ch, N));
// This code is contributed by SoumikMondal
</script>
Time complexity: O(N) where N is length of string
Auxiliary Space: O(1)
Approach#2: Using the count() method
this approach Uses the count() method to count the number of occurrences of the target character in the string. If the count is less than N, return -1. Otherwise, use a loop to find the Nth occurrence of the target character.Once the Nth occurrence is found, return its index.
Algorithm
1. First, it uses the count() method to count the number of occurrences of the target character in the string.
2. If the count is less than N, it means that the Nth occurrence is not present in the string, so the function returns -1.
3. Otherwise, it initializes the index variable to -1, and uses a loop to find the Nth occurrence of the target character. The loop runs N times, and on each iteration, it uses the index() method to find the next occurrence of the target character in the string, starting from the position after the previous occurrence.
4. Once the Nth occurrence is found, the function returns its index.
C++
#include <iostream>
using namespace std;
int find_nth_occurrence(string str, char ch, int N) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ch) {
count++;
if (count == N) {
return i;
}
}
}
return -1;
}
int main() {
string str = "geeks";
char ch = 'e';
int N = 2;
cout << find_nth_occurrence(str, ch, N) << endl;
return 0;
}
Java
import java.util.Scanner;
public class GFG {
public static int findNthOccurrence(String str, char ch, int N) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
if (count == N) {
return i;
}
}
}
return -1;
}
public static void main(String[] args) {
String str = "geeks";
char ch = 'e';
int N = 2;
System.out.println(findNthOccurrence(str, ch, N));
}
}
Python3
def find_nth_occurrence(str, ch, N):
count = str.count(ch)
if count < N:
return -1
index = -1
for i in range(N):
index = str.index(ch, index+1)
return index
str = "geeks"
ch = 'e'
N = 2
print(find_nth_occurrence(str, ch, N))
C#
using System;
public class GFG {
// Function to find the Nth occurrence of a character in
// a string
public static int FindNthOccurrence(string str, char ch,
int N)
{
// Initialize a variable named count to 0.
int count = 0;
// Loop through each character in the string str
// using a for loop.
for (int i = 0; i < str.Length; i++) {
// If the current character is equal to the
// character ch,
if (str[i] == ch) {
// Increment the count variable by 1.
count++;
// If the count variable is equal to N,
if (count == N) {
// Return the index of the current
// character.
return i;
}
}
}
return -1;
}
public static void Main()
{
string str = "geeks";
char ch = 'e';
int N = 2;
Console.WriteLine(FindNthOccurrence(str, ch, N));
}
}
JavaScript
function findNthOccurrence(str, ch, N) {
// Initialize a variable named count to 0.
let count = 0;
// Loop through each character in the string str using a for loop.
for (let i = 0; i < str.length; i++) {
// If the current character is equal to the character ch,
if (str[i] === ch) {
// Increment the count variable by 1.
count++;
// If the count variable is equal to N,
if (count === N) {
// Return the index of the current character.
return i;
}
}
}
return -1;
}
let str = "geeks";
let ch = 'e';
let N = 2;
console.log(findNthOccurrence(str, ch, N));
Time complexity: O(n), where n is the length of the string.
Auxiliary Space: O(1).
Similar Reads
Count Occurrences of a Given Character in a String
Given a string S and a character 'c', the task is to count the occurrence of the given character in the string.Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str.Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times in
6 min read
Find the number of occurrences of a character upto preceding position
Given a string S of length N and an integer P(1?P?N) denoting the position of a character in the string. The task is to find the number of occurrences of the character present at position P up to P-1 index. Examples: Input : S = "ababababab", P = 9 Output : 4 Character at P is 'a'. Number of occurre
7 min read
Find maximum occurring character in a string
Given string str. The task is to find the maximum occurring character in the string str.Examples:Input: geeksforgeeksOutput: eExplanation: 'e' occurs 4 times in the stringInput: testOutput: tExplanation: 't' occurs 2 times in the stringReturn the maximum occurring character in an input string using
8 min read
Python - Replacing Nth occurrence of multiple characters in a String with the given character
Replacing the Nth occurrence of multiple characters in a string with a given character involves identifying and counting specific character occurrences.Using a Loop and find()Using a loop and find() method allows us to search for the first occurrence of a substring within each list element. This app
2 min read
Kth character from the Nth string obtained by the given operations
Given two positive integers N and K, the task is to find the Kth character of a string obtained by performing the following operation on a string S( initially "A") N times. Every ith operation generates following string (Si): Si = Si - 1 + 'B' + rev(comp(Si - 1)) where, comp() denotes the complement
6 min read
Queries to find the last non-repeating character in the sub-string of a given string
Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}
11 min read
Find the Suffix Array of given String with no repeating character
Given a string str of size N, the task is to find the suffix array of the given string. Note: A suffix array is a sorted array of all suffixes of a given string. Examples: Input: str = "prince"Output: 4 5 2 3 0 1Explanation: The suffixes are0 prince 4 ce1 rince Sort the suffixes 5 e 2 ince ---------
6 min read
Find Character Frequencies in Order of Occurrence
Given string s containing only lowercase characters, the task is to print the characters along with their frequency in the order of their occurrence and in the given format explained in the examples below.Examples: Input: s = "geeksforgeeks"Output: g2 e4 k2 s2 f1 o1 r1Input: str = "elephant"Output:
13 min read
Print the string after the specified character has occurred given no. of times
Given a string, a character, and a count, the task is to print the string after the specified character has occurred count number of times. Print "Empty string" in case of any unsatisfying conditions. (Given character is not present, or present but less than given count, or given count completes on
5 min read
Find last index of a character in a string
Given a string str and a character x, find last index of x in str. Examples : Input : str = "geeks", x = 'e' Output : 2 Last index of 'e' in "geeks" is: 2 Input : str = "Hello world!", x = 'o' Output : 7 Last index of 'o' is: 7 Recommended PracticeLast index of a character in the stringTry It! Metho
8 min read