如何从字符串中删除模式的所有实例?
string str = "red tuna, blue tuna, black tuna, one tuna";
string pattern = "tuna";
答案 0 :(得分:12)
从字符串
中删除模式的所有实例#include <string>
#include <iostream>
using namespace std;
void removeSubstrs(string& s, string& p) {
string::size_type n = p.length();
for (string::size_type i = s.find(p);
i != string::npos;
i = s.find(p))
s.erase(i, n);
}
int main() {
string str = "red tuna, blue tuna, black tuna, one tuna";
string pattern = "tuna";
removeSubstrs(str, pattern);
cout << str << endl;
}
答案 1 :(得分:7)
这是一个基本问题,您最好查看标准库中的string功能。
#include <iostream>
#include <string>
int main() {
std::string str = "red tuna, blue tuna, black tuna, one tuna";
std::string pattern = "tuna";
std::string::size_type i = str.find(pattern);
while (i != std::string::npos) {
str.erase(i, pattern.length());
i = str.find(pattern, i);
}
std::cout << str;
}
从C ++ 11开始,你有另一种解决方案(感谢Joachim提醒我这一点)基于regular expressions
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string str = "red tuna, blue tuna, black tuna, one tuna";
std::regex pattern("tuna");
std::cout << std::regex_replace(str, pattern, "");
}
答案 2 :(得分:3)
尝试类似:
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
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(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
答案 3 :(得分:0)
这是更好理解的基本逻辑 这是c ++中的代码
string s,x; //s is the string , x is the substring
int a,l;
cin>>s>>x;
l=x.length();
while(true)
{
a=s.find(x);
if(a==-1)
{break;} // if substring is not found
else
{
s.erase(a,l); //if substring is found
}
}
if(s.length()==0) // if string length becomes null printing 0
cout<<0<<"\n";
else
cout<<s<<endl; // else printing the string
示例: 输入shahaha 输出shha
答案 4 :(得分:0)
一种更快的算法,一次构建一个字符并检查结尾是否与子字符串匹配。以下在 o(substring * string) 中运行,而上述解决方案在 o(s^2/t) 中运行。
string S, T;
cin >> S >> T;
/* Build R, the result string, one character at a time. */
string R;
for (int i = 0; i < S.size(); i++) {
R += S[i];
/* If the end of R matches T then delete it. */
if (R.size() >= T.size() && R.substr(R.size() - T.size()) == T) {
R.resize(R.size() - T.size());
}
}
cout << R << endl;