
在本文中,我们将解决从给定字符串中删除给定单词的问题。例如 –
Input : str = “remove a given word ”, word = “ remove ”Output : “ a given word ”Input : str = “ god is everywhere ”, word = “ is ”Output : “ god everywhere ”
寻找解决方案的方法
例如,我们可以使用一种简单的方法从字符串中删除单词。
首先,将二维矩阵形式的给定字符串,其中每个单词存储在每一行中。在矩阵中查找该单词,并将该行替换为该单词所在的空字符。最后,打印重新排序的字符串。
示例
#include 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] != ' '; i++) { if (str[i] == ' ') { matrix[k][j] = ' '; 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] = ' '; j = 0; for (i = 0; i < k + 1; i++) { if (strcmp (matrix[i], word) == 0) { matrix[i][j] = '