Nov 1, 2016 at 9:50am UTC
I am trying to count the number of times a given substring is present within a string. My could always gives 0, unless I have the same substring and string, which then it gives 1.
Help...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str_to_search, str;
int count = 0;
cout << "Please enter the string to search: \n" ;
getline(cin, str_to_search);
cout << "Enter the substring to find: \n" ;
getline(cin, str);
int nPos = str.find(str_to_search, 0); // fist occurrence
while (nPos != string::npos)
{
count++;
nPos = str.find(str_to_search, nPos + 1);
}
cout << count << endl;
system("Pause" );
}
Last edited on Nov 1, 2016 at 9:50am UTC
Nov 1, 2016 at 9:59am UTC
Think about it - you are seaching for str in str_to_search.
You have these the wrong way round in lines 15 and 20.
Nov 1, 2016 at 10:12am UTC
Actually, all he/she had to do was reverse the roles of str and str_to_search in the two lines 15 and 20! Why obfuscate that?
Nov 1, 2016 at 10:17am UTC
This works for some reason, I just had to move int count = 0...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str_to_search, str;
cout << "Please enter the string to search: \n" ;
getline(cin, str_to_search);
cout << "Enter the substring to find: \n" ;
getline(cin, str);
int count = 0;
int nPos = str.find(str_to_search, 0);
while (nPos != string::npos)
{
count++;
nPos = str.find(str_to_search, nPos + 1);
}
cout << "There is a total of " << count << endl;
system("pause" );
return 0;
}
Last edited on Nov 1, 2016 at 10:18am UTC