My issue
Find Kth Character Position
Given a string s1, a character c1, and an integer k, find and print the position of the
k
kth occurrence of the character c1 in the string s1. If the
k
kth occurrence does not exist, print -1.
Input Format
The first line contains the string s1, the character c1, and the integer k separated by spaces.
Output Format
An integer representing the position of the
k
kth occurrence of c1 in s1.
If the
k
kth occurrence does not exist, print -1.
Sample 1:
Input
Output
HelloHowyoudoing H 2
5
My code
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1;
char c1;
int k;
// Read the input: string s1, character c1, and integer k
cin >> s1 >> c1 >> k;
int count = 0;
// Iterate through the string to find the k-th occurrence of c1
for (int i = 0; i < s1.length(); i++) {
if (s1[i] == c1) {
count++;
if (count == k) {
// Print the position (1-based index)
cout << i + 1 << endl;
return 0;
}
}
}
// If k-th occurrence is not found, print -1
cout << -1 << endl;
return 0;
}
Learning course: Data structures & Algorithms lab
Problem Link: Find Kth Character Position in Data structures & Algorithms lab