I need some help

Hi guys, I need some help.
I am not pretty good with arrays and i need some help
Lets say we have a sentence S and the words w1 and w2.
I want to replace all the words w1 in the sentence with the words w2.
Example : S : "I have lots of apples apples apples."
w1 : "apples" ; w2 : ""fruits";
The sentence will become : "I have lots of fruits fruits fruits.";
(I am a begginer)

Put your sentence in a string (use getline).

Use the 'find' and 'replace' member functions for that string.
closed account (48T7M4Gy)
http://www.cplusplus.com/reference/string/string/
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
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <conio.h>
#include <string>
#include <exception>

using namespace std;

int main(int argc,char* argv[])
{
	string str("I have lots of apples apples apples.");
	string w1, w2;
	//getline(cin, str);
	cout<< "str = \"" << str << '\"' << endl;
	cout << "Enter the word to be substituted: ";
	cin >> w1;
	int count(0);
	while(str.find(w1)!=string::npos)
	{
		count++;
		if(count == 1)
		{
			cout << "Enter the word to substitute: ";
			cin >> w2;
		}
		try
		{
			str.replace(str.find(w1),w1.length(),w2);
		}
		catch(out_of_range &oor)
		{
			cerr << oor.what() << endl;
			abort();
		}
		catch(...)
		{
			cerr << "some another error has been found\n";
			abort();
		}
	}
	if (count == 0)cout << "This word hasn't been found in the sentence, there is nothing to be substituted.\n";
	else cout << "the new str = \"" << str << '\"' << endl;
	cout<<"\nBye...";
	_getch();
	return 0;
}
Topic archived. No new replies allowed.