Using count()
Apr 26, 2015 at 7:43pm UTC
Hello. Is there any way I could do this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
#include<string>
using namespace std;
int main()
{
string first;
cin >> first;
string second;
cin >> second;
count(first.begin(), first.end(), second);
system("Pause" );
return 0;
}
Apr 26, 2015 at 8:27pm UTC
What do you attempt to do?
You are comparing a std::string to a char
.
Perhaps string::find.
Apr 27, 2015 at 3:24pm UTC
To use it with two strings instead of string and char. Maybe char pointer?
Apr 27, 2015 at 6:05pm UTC
What do you want to achieve ?
Apr 28, 2015 at 2:47pm UTC
To find the occurrences of the second string.
Apr 28, 2015 at 4:03pm UTC
1 2 3 4 5 6 7
size_t count { 0 };
auto pos = first.find( second );
while ( std::string::npos != pos ) {
++counter;
// auto next { pos + something };
pos = first.find( second, next );
}
The
something depends on whether you allow overlapping matches. E.g. does "aaaaaa" contain "aa" for 3 or 5 times?
Apr 28, 2015 at 5:15pm UTC
You mean 3 or 6? 3. But isn't find() for finding the position?
Apr 28, 2015 at 8:24pm UTC
3 or 5:
If second occurs in first, then there must be a position where it occurs. There is nothing wrong in using the find for that.
If an occurrence has already been found, the rest of the first might still contain other occurrences. Hence the loop.
If overlaps were allowed, then the
something would be 1 -- start search from the next character after the current position. You don't want overlaps, so you must add more than 1.
Apr 29, 2015 at 9:06am UTC
So, it should be something like this?
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>
#include<algorithm>
using namespace std;
int main()
{
string first;
string second;
getline(cin, first);
getline(cin, second);
int counter = 0;
int pos = first.find(second);
while (string::npos != pos)
{
++counter;
int next = pos + second.length();
pos = first.find(second, next);
}
cout << counter << endl;
system("Pause" );
return 0;
}
Isn't for loop better for this case?
Apr 29, 2015 at 10:36am UTC
Yes.
While we are not at the end yet.
vs.
For how many times, exactly?
You can rewrite it as a for-loop, but it is hardly as neat.
Apr 29, 2015 at 12:00pm UTC
1 2 3 4 5 6 7
int counter = 0;
int pos = first.find(second);
for (int i = pos; pos!=string::npos; counter++)
{
int next = pos + second.length();
pos = first.find(second, next);
}
So, string::npos means the end of the string?
Topic archived. No new replies allowed.