c++ index of nth occurence

To find the index of the nth occurrence of a specific character in a string in C++, you can follow these steps:

  1. Declare and initialize variables:
  2. Define a string variable str to hold the input string.
  3. Define a character variable ch to hold the character whose occurrence we want to find.
  4. Define an integer variable n to hold the nth occurrence we are looking for.
  5. Define an integer variable count and set it to 0. This variable will keep track of the number of occurrences found.

  6. Iterate over the characters in the string:

  7. Use a for loop and iterate from 0 to the length of the string minus 1.
  8. Inside the loop, check if the current character is the same as the character ch.
  9. If it is, increment the count variable by 1.
  10. Check if the count variable is equal to n. If it is, return the index of the current character.

  11. Handle the case when the nth occurrence is not found:

  12. If the loop completes without finding the nth occurrence, return -1 to indicate that the character was not found.

Here is the code snippet that implements the above steps:

#include <iostream>
using namespace std;

int findNthOccurrence(const 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 = "Hello, World!";
    char ch = 'o';
    int n = 2;

    int index = findNthOccurrence(str, ch, n);
    if (index != -1) {
        cout << "The index of the " << n << "th occurrence of '" << ch << "' in the string is: " << index << endl;
    } else {
        cout << "The " << n << "th occurrence of '" << ch << "' was not found in the string." << endl;
    }

    return 0;
}

This code snippet defines a function findNthOccurrence that takes a string str, a character ch, and an integer n as input arguments. The function returns the index of the nth occurrence of the character in the string, or -1 if the nth occurrence is not found. The main function demonstrates the usage of this function by finding the index of the second occurrence of the character 'o' in the string "Hello, World!".