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 updated 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> // Includes all standard libraries

using namespace std; // Using the standard namespace

// Function to remove occurrences of 'w' from 's'
string test(string s, string w) {
    // While 'w' is found in 's', replace it with an empty string
    while (s.find(w) != string::npos)
        s.replace(s.find(w), w.length(), "");

    return s; // Return the modified string 's'
}

int main() {
    string text = "Exercises Practice Solution"; // Original string
    string word = "Solution"; // Word to be removed from 'text'

    cout << "String: " << text; // Display original string
    cout << "\nWord to remove: " << word; // Display word to be removed
    cout << "\nNew string, after removing the said word:\n";
    cout << test(text, word) << endl; // Call 'test' function and display modified string

    // Repeat the same process for different words to be removed
    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; 

    // The main function displays original strings, words to be removed,
    // and the resulting strings after removing those words.
}

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?



Follow us on Facebook and Twitter for latest update.