使用 C++ 從字串中移除指定單詞
在本文中,我們將解決從給定字串中移除給定單詞的問題。例如 -
Input : str = “remove a given word ”, word = “ remove ” Output : “ a given word ” Input : str = “ god is everywhere ”, word = “ is ” Output : “ god everywhere ”
尋找解決方案的方法
例如,我們可以使用一種簡單的方法從字串中移除單詞。
- 首先,將給定的字串放入二維矩陣形式,每個單詞儲存在一行中。
- 在矩陣中查詢單詞,並用空字元替換單詞所在的行。
- 最後,列印重新排序的字串。
示例
#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;
}輸出
a given word god everywhere
上述程式碼的解釋
- 使用一些值初始化字串和陣列,並呼叫函式以移除給定單詞。
- 使用迴圈將字串的每個單詞放入二維矩陣的每一行,將每個字元儲存在每個塊中,直到找到空格。
- 使用 strcmp() 函式將字串與單詞進行比較,並在找到單詞的行中放入空值。
- 最後,列印字串,列印矩陣的每一行。
結論
本文討論了從字串中移除給定單詞,我們透過將字串儲存在二維矩陣中,然後用空值替換單詞來解決問題。我們使用 C++ 程式碼解決了這個問題。但是,我們可以使用其他任何語言(如 C、Java、Python 等)來解決相同的問題。希望本文對您有所幫助。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP