Open In App

Find the Nth occurrence of a character in the given String

Improve
Improve
Like Article
Like
Save
Share
Report

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>


Output

2



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));


Output

2



Time complexity: O(n), where n is the length of the string.
Auxiliary Space: O(1).



Last Updated : 22 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads