這裏我有一個像這樣的字符串WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
我想要刪除所有wub
字形式並獲得這個結果WE ARE THE CHAMPIONS MY FRIEND
。
在C++中有沒有什麼特別的功能可以做到這一點,我發現string::erase
,但接力並沒有幫助我!
我可以用for
循環做到這一點,並找到這個詞形式字符串,然後刪除它,但我正在尋找更好的方式。 有沒有這樣做的功能?如何從C++中刪除一個字符串形式的字符串
回答
你可以使用std::regex_replace
:
std::string s1 = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
std::regex target("(WUB)+");
std::string replacement = " ";
std::string s2 = std::regex_replace(s1, target, replacement);
鑑於OP的期望輸出,我認爲替換字符串應該包含一個空格。 – 2014-09-24 14:51:01
@FredLarson:好點 - 我會更新答案。 – 2014-09-24 14:52:25
啊,更新後的正則表達式會替換一個空格的連續匹配。好工作。 – 2014-09-24 14:55:54
使用boost ::算法:: replace_all
#include <iostream>
#include <string>
#include <boost/algorithm/string/replace.hpp>
int main()
{
std::string input="WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
boost::algorithm::replace_all(input, "WUB", " ");
std::cout << input << std::endl;
return 0;
}
您能否擴展您的答案以舉例說明這將如何應用? – 2014-09-24 14:59:52
增加了一個例子 – 2014-09-24 15:09:41
謝謝 - 這是有幫助的。我想這完全不能應付OP的例子,即'WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB' - >'我們是我的朋友們的冠軍'? – 2014-09-24 15:11:30
刪除所有出現:
#include <iostream>
std::string removeAll(std::string str, const std::string& from) {
size_t start_pos = 0;
while((start_pos = str.find(from)) != std::string::npos) {
str.erase(start_pos, from.length());
}
return str;
}
int main() {
std::string s = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
s = removeAll(s, "WUB");
return 0;
}
替換所有出現:
std::string replaceAll(std::string str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
return str;
}
int main() {
std::string s = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
s = replaceAll(s, "WUB", " ");
/* replace spaces */
s = replaceAll(s, " ", " ");
return 0;
}
從問題中的例子看來,OP似乎希望用一個空格替換一個或多個連續出現的「WUB」。 – 2014-09-24 14:57:25
@PaulR code added – 4pie0 2014-09-24 15:02:18
看起來不錯,除了「WUBWUB」應該只給一個空間,我認爲,不是兩個? – 2014-09-24 15:09:09
- 1. 從c字符串中刪除字符
- 2. 從字符串中刪除字符C
- 3. C從字符串中刪除字符
- 4. C++從字符串中刪除字符
- 5. 從C字符串中刪除字符
- 6. 在C++中刪除字符形成一個字符串
- 7. 從一個字符串中刪除一個子字符串
- 8. 從字符串中刪除字符串
- 9. 從字符串中刪除字符串
- 10. 如何從字符串中刪除動態字符字符串?
- 11. 如何從C#字符串中刪除一些字符?
- 12. 如何從字符串中刪除第一個字c
- 13. 如何從字符串中刪除多個子字符串?
- 14. 從字符串C#刪除點字符
- 15. 如何從C++中的字符串中刪除字符?
- 16. 從一個字符串中刪除一個子字符串,使用memmove在C
- 17. C刪除字符串中的字符
- 18. 刪除c字符串中的字符
- 19. 如何從字符串[python]中刪除一個字符?
- 20. 如何從字符串中刪除一個字符?
- 21. 如何從Python中的字符串中刪除字符串?
- 22. 如何從tcl中的字符串中刪除子字符串
- 23. 如何從python中的字符串中刪除子字符串?
- 24. 如何從javascript中的字符串中刪除子字符串?
- 25. 刪除一個字符串的字符
- 26. 從字符串中刪除字符串模式和符號
- 27. 從另一個字符串中刪除字符串中的字符的功能
- 28. 從C中的字符串開頭刪除子字符串
- 29. 如何從字符串中刪除數字符在C#中
- 30. 如何使用C中的baskspace從字符串中刪除一個字符?
你可以使用'的std :: regex_replace'? – 2014-09-24 14:42:10
或'boost :: algorithm :: replace_all' – Bogdan 2014-09-24 14:43:11