Help with the find function of string

Hello, I had an assignment about string type sadly I couldn't complete it
Can somebody tell me what is my mistake

Question is:
(A) Write a function named countThe that takes a string as an input parameter and returns how many “the” was repeated in the string. You should use “String Type” functions discussed in chapter 8 (find, substr, length, swap)

(B) Write a program that reads a string from the user and display the count of “the” in the sentence.

Example for the output
Enter a string:
the name of the book is: the programming Concepts

# of the = 3


And that's what I have done
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
26
27
28
29
30
31
32
#include <iostream>
#include <string>
using namespace std;
int CountThe(string st1, string st2);
int main()
{
	string st1, st2="the";

	cout<<"Enter a string:\n";
	getline(cin, st1);

	
	cout<<"# of the = "<<CountThe(st1, st2)<<endl;
	
	return 0;
}

int CountThe(string st1, string st2)
{
	int NumOfThe=0, position=0;
	string str1, str2="the";

	position = str1.find(str2, position);
	while(position < str1.length())
	{
		if(str1.find(str2, position))
			NumOfThe++;
		position++;
		position = str1.find(str2, position);
	}
	return NumOfThe;
}
Last edited on
This code

1
2
3
4
int CountThe(string st1, string st2)
{
	int NumOfThe=0, position=0;
	string str1, str2="the";


1) has no any sense because it does not use values of the parameters; 2) is invalid because str1 is not initialized.

The functiom can be rewritten the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
size_t CountThe( const std::string &str1, const std::string &str2 )
{
	size_t count = 0;
	std::string::size_type pos = 0;

	while ( ( pos = str1.find( str2, pos ) ) != std::string::npos )
	{
		count++;
		pos += str2.size();
	}

	return count;
}

Last edited on
Topic archived. No new replies allowed.