w3resource

C++ String Exercises: Remove a word from a given string

C++ String: Exercise-34 with Solution

Write a C++ program that removes a specific word from a given string. Return the new string.

Test Data:
("Exercises Practice Solution", "Solution") -> "Exercises Practice"
("Exercises Practice Solution", "Practice ") -> "Exercises Solution"
("Exercises Practice Solution", " Solution") -> " Practice Solution"

Sample Solution:

C++ Code:

#include <bits/stdc++.h>

using namespace std;
string test(std::string s, std::string w)
{
       while (s.find(w) != string::npos)
        s.replace(s.find(w), w.length(), "");
        return s;
}
int main()
{
	string text = "Exercises Practice Solution";
	string word ="Solution";
	cout << "String: " << text;
	cout << "\nWord to remove: " << word;
	cout << "\nNew string, after removing the said word:\n";
	cout << test(text, word) << endl;
    word ="Practice";
	cout << "\nString: " << text;
	cout << "\nWord to remove: " << word;
	cout << "\nNew string, after removing the said word:\n";
	cout << test(text, word) << endl;
	word ="Exercises";
	cout << "\nString: " << text;
	cout << "\nWord to remove: " << word;
	cout << "\nNew string, after removing the said word:\n";
	cout << test(text, word) << endl; 	  	 
}

Sample Output:

String: Exercises Practice Solution
Word to remove: Solution
New string, after removing the said word:
Exercises Practice

String: Exercises Practice Solution
Word to remove: Practice
New string, after removing the said word:
Exercises  Solution

String: Exercises Practice Solution
Word to remove: Exercises
New string, after removing the said word:
 Practice Solution

Flowchart:

Flowchart: Remove a word from a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Check first string contains letters from the second.

Next C++ Exercise: Reverse the words in a string that have odd lengths.

What is the difficulty level of this exercise?



Share this Tutorial / Exercise on : Facebook and Twitter

C++ Programming: Tips of the Day

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Ref: https://bit.ly/3niU71x