Remove a Given Word from a String using C++



In this article, we’ll be solving the problem of removing a given word from a given string. For example −

Input : str = “remove a given word ”, word = “ remove ” Output : “ a given word ” Input : str = “ god is everywhere ”, word = “ is ” Output : “ god everywhere ”

Approach to find The Solution

For example, we can use a simple approach to remove a word from a string.

  • First, put the given string in 2-D matrix form, where each word is stored in each row.
  • Find the word in the matrix and replace that row with the null character where the word.
  • Finally, print the reordered string.

Example

#include <bits/stdc++.h> using namespace std; int remove_word (string str, char word[]) {    char matrix[10][30];    int i = 0, j = 0, k = 0, len1 = 0, len2 = 0;    // putting each word of string into the rows of the 2-D matrix.    for (i = 0; str[i] != '\0'; i++) {       if (str[i] == ' ') {          matrix[k][j] = '\0';          k++;          j = 0;       }else{          matrix[k][j] = str[i];          j++;       }    }    // looking for the word in a given string and putting a null character when the word is found.    matrix[k][j] = '\0';    j = 0;    for (i = 0; i < k + 1; i++) {       if (strcmp (matrix[i], word) == 0) {          matrix[i][j] = '\0';       }    }    j = 0;    // printing the reordered string.    for (i = 0; i < k + 1; i++){       if (matrix[i][j] == '\0')          continue;       else          cout << matrix[i] << " ";    }    cout << "\n"; } int main () {    char str1[] = "remove a given word", word1[] = "remove";    char str2[] = "god is everywhere", word2[]="is";    // calling a function to remove a word from a string and print it.    remove_word (str1, word1);    remove_word (str2, word2);    return 0; }

Output

a given word god everywhere

Explanation of the above code

  • Initializing string and array with some values and calling function to remove given the word.
  • Putting each word of string in each row of a 2-D matrix using a loop stored each character in each block until space is found.
  • Comparing string with a word using strcmp() function and put null value in the row where the word is found.
  • Finally, printing the string with printing each row of the matrix.

Conclusion

This article discussed removing a given word from a String where we solve the problem by storing the string in a 2-D matrix and then replacing the word with a null value. We solved this problem using C++ code. However, we can solve the same problem using any other language like C, Java, Python, etc. Hope you find this article helpful.

Updated on: 2021-11-26T10:46:47+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements