change a word into another word using strings

I have to replace a word into another word using strings for an assignment.
We haven't learned [string.replace], but I'm stuck right now.
Here's the code I have come up with so far:
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
#include <iostream>  
#include <iomanip>  
#include <cmath>  
#include <string>  
	using namespace std;  

int main()  {  
	// Create a text string
	string userString = "";
	string str1 = "hate";
	string finalSentence = "";

	// Prompt the user
	cout << "This program will repace the word 'hate' into 'love' from any sentences the user enters." << endl;
	cout << "Please follow the direction correctly, and type correct input." << endl;
	cout << endl << endl;
	
	// Printing the input
	cout << "Please enter a sentence: " << endl;  
	getline(cin, userString);

	if(userString.find(userString) = "hate")	{
		finalSentence += "love";
	}
	cout << finalSentence << endl;
	
	system("pause");
	return 0;
}
As an example of how it could be done you may use the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	std::string userString;
	std::string finalSentence;
	const std::string source( "hate" );
	const std::string target( "love" );

//	here is some code for entering userString

	finalSentence = userString;

	std::string::size_type pos = 0;

	while ( ( pos = finalSentence.find( source, pos ) ) != std::string::npos )
	{
		finalSentence.replace( pos, source.size(), target );
		pos += target.size();
	}
Last edited on
Umm thanks for your suggestion but we haven't learned using :: in our source code so I don't think that will work...
Isn't there any other possible way?? :(
No problem. Include in your program using directive using namespace std; and remove everywhere std::
Topic archived. No new replies allowed.