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)
#include <iostream>
#include <conio.h>
#include <string>
#include <exception>
usingnamespace 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;
}