Using count()

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;
}
What do you attempt to do?

You are comparing a std::string to a char.

Perhaps string::find.
To use it with two strings instead of string and char. Maybe char pointer?
What do you want to achieve?
To find the occurrences of the second string.
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?
You mean 3 or 6? 3. But isn't find() for finding the position?
3 or 5:
aaaaaa
aa
 aa
  aa
   aa
    aa

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.
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?
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.
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.