为什么我不能像这样在 string.erase 中调用 string.find:str.erase(str.find(a[1]),str.size())
?
编辑:添加代码
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// html tags
string tags[5]={"<!--...-->","<!DOCTYPE>","<a>","<abbr>","<acronym>"};
//
//check if string exists
int boolStringExists(string a, string b)
{
if(a.find(b)>0)
{
return 1;
}
if(a.find(b)<=0)
{
return 0;
}
}
//erase tag from string a
void eraseTags(string a,string b[])
{
for(int i=0; i<5;i++)
{
int x=(boolStringExists(a,b[i]));
while (x>0)
{
a.erase(a.find(b[i]),b[i].size());
x=(boolStringExists(a,b[i]));
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
fstream file;
file.open("h:\\a.htm");
string k,m;
while(getline(file, k))
m += k ;
eraseTags(m,tags);
return 0;
}
给出此消息:“此应用程序已请求运行时以异常方式终止它。请联系应用程序的支持团队以获取更多信息。”
最佳答案
如果没有找到字符串,find
返回string::npos
,然后您的代码将无法运行并会出现运行时错误。看到这给出了错误:https://ideone.com/NEhqn
最好这样写:
size_t pos = str.find(a[1]);
if ( pos != std::string::npos)
str.erase(pos); //str.size() is not needed!
现在这不会给出错误:https://ideone.com/IF2Hy
关于c++ - 你如何使用 string.erase 和 string.find?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5309994/