The string class has a built-in find() function, but only finds the first time t
ID: 3681074 • Letter: T
Question
The string class has a built-in find() function, but only finds the first time this happens in the string. Start from the findNth.cpp on the website, and make the findNth() function to return the index of the first letter of the Nth match in the string. (Much the same way the string find() function returns the index of the first match in the string.) You may assume N is 1 or larger. If there is no Nth pattern, return -1.
Example 1 (user input is bold):
Enter the string: 01x34x6x89x
Enter the pattern: x
Enter n: 1
2
Example 2 (user input is bold):
Enter the string: 01x34x6x89x
Enter the pattern: x
Enter n: 3
7
Example 3 (user input is bold):
Enter the string: 01x34x6x89x
Enter the pattern: x
Enter n: 20
1
Example 4 (user input is bold):
Enter the string: 0xxx45xx89x
Enter the pattern: xx
Enter n: 3
6
findNth.cpp:
Explanation / Answer
#include <iostream>
#include <cstdlib>
using namespace std;
int findNth(string str, string pattern, int n);
int main()
{
string str, pat;
int n;
cout << "Enter the string: ";
getline(cin, str);
cout << "Enter the pattern: ";
getline(cin, pat);
cout << "Enter n: ";
cin >> n;
cout << findNth(str, pat, n) << endl;
return 0;
}
int findNth(string str, string pattern, int n)
{
int len = str.length();
int m = pattern.length();
int count = 0;
for (int i = 0; i <= len-m; ) {
int j = 0;
while (j < m && str[i+j] == pattern[j]) {
++j;
}
if (j == m) { // match found
// increment count
count++;
if(count == n) //
return i;
}
i++;
}
return -1;
}
/*
Output:
Enter the string: 0xxx45xx89x
Enter the pattern: xx
Enter n: 3
6
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.