Replacing words in a string

I want to write a program that replaces words in a string. For example, if the user inputs "hi" as a word to replace and then "hello" as a replacement word, then they enter a phrase such as "hi world!" the program would then output a message as "hello world!"



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>
using namespace std;
#include <string>
int main(){
  string word;
  string replace;
  string phrase;
  string newphrase;  

  //User input
  cout<<"Enter a word to replace: ";
  cin>>word;   //hi
  cout<<"Enter a replacement word: ";
  cin>>replace;  //hello
  cout<<"Enter your phrase: ";
  cin.ignore();
  getline(cin, phrase);  //hi world
  
  
  //Insert code here

  cout<<"New Phrase: "<<newPhrase; //hello world
}
First you need to find the right pos with the string find method then you can replace it.
https://www.cplusplus.com/reference/string/string/replace/
Do you mean replace a word or replace a sequence of characters?

Do you want "hiworld" to be "helloworld" or not changed as hi are the starting chars and not a word in its own right?

I want to replace a word. I want "hi world" to become "hello world". In this example hi is the word.
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
#include <iostream>
#include <string>
using namespace std;

int main()
{
   string word, replacement, phrase;

   cout << "Enter a word to replace: ";   getline( cin, word );
   cout << "Enter a replacement word: ";   getline( cin, replacement );
   cout << "Enter a phrase: ";   getline(cin, phrase);
   for ( int p = 0; ( p = phrase.find( word, p ) ) != string::npos; )  
   {
      int q = p + word.size();
      if ( ( p == 0 || !isalnum( phrase[p-1] ) ) && ( q == phrase.size() || !isalnum( phrase[q] ) ) )
      {
         phrase.replace( p, word.size(), replacement );
         p += replacement.size();
      }
      else
      {
         p += word.size();
      }
   }
   cout << phrase << '\n';
}

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
#include <iostream>
#include <string>
#include <sstream>

int main()
{
	std::string word, replacement, phrase;

	std::cout << "Enter a word to replace: ";
	std::getline(std::cin, word);

	std::cout << "Enter a replacement word: ";
	std::getline(std::cin, replacement);

	std::cout << "Enter a phrase: ";
	std::getline(std::cin, phrase);

	std::ostringstream oss;
	std::istringstream iss(phrase);

	for (std::string wrd; iss >> wrd; oss << (wrd == word ? replacement : wrd))
		if (oss.tellp())
			oss << ' ';

	phrase = oss.str();
	std::cout << phrase << '\n';
}



Enter a word to replace: hi
Enter a replacement word: hello
Enter a phrase: hi world
hello world

Topic archived. No new replies allowed.