如何在c++中从字符串中删除子字符串
How to delete a substring form a string in c++
这里有一个类似于WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
的字符串,我想从中删除所有wub
单词,并得到这个结果WE ARE THE CHAMPIONS MY FRIEND
c++中有什么特殊的函数可以做到这一点吗?我找到了string::erase
,但那个继电器对我没有帮助
我可以用for
循环找到这个单词形式的字符串,然后删除它,但我正在寻找更好的方法。有什么功能可以做到这一点吗???
您可以使用std::regex_replace
:
std::string s1 = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
std::regex target("(WUB)+");
std::string replacement = " ";
std::string s2 = std::regex_replace(s1, target, replacement);
现场演示
使用boost::algorithm::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;
}
清除所有发生:
#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;
}
http://ideone.com/Hg7Kwa
替换所有出现的情况:
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;
}
http://ideone.com/Yc8rGv
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 如何从给定字符串中删除第二次和第三次出现的$
- 在C++的字符串中搜索和删除某些字符
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 使用另一个字符串从字符串中删除空格
- 删除/替换C++字符串中的多字符 (ÿû)
- 删除所有字符串后如何恢复 QStringList?
- 如何删除字符串中的前 2 个字符(如果它有"-")
- 根据新的行分隔符从字符串中删除子字符串
- C ++,如何从控制台中输入的字符串中删除字母?
- 删除字符串后C++检测到堆损坏
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 如何在 c++ 中删除字符串中的某些字符?
- 删除字符串数组
- 删除字符串中具有相同值的任何相邻字母"pair"
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- 如何使用双黑斜杠从字符串中删除单反斜杠
- 如何在编译时从string_view中删除子字符串?
- 从文件中读取多行.txt字符串删除空格并创建新文件进行输出
- c字符串 删除非字母/非空格字符 - C++