C++ 如何使用string.erase和string.find?
为什么我不能在string.erase中这样调用string.find:C++ 如何使用string.erase和string.find?,c++,string,C++,String,为什么我不能在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]={"<!--...-->","&l
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;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
//html标记
字符串标记[5]={“”、“”、“”、“”、“”};
//
//检查字符串是否存在
int boolStringExists(字符串a、字符串b)
{
如果(a.find(b)>0)
{
返回1;
}
如果(a.find(b)调用没有问题(假设a[1]
存在并且在str
中至少找到一次)
该调用没有问题(假设a[1]
存在并且在str
中至少找到一次)
似乎要删除str.find(a[1])之后的所有内容。在这种情况下,可以忽略第二个参数
#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
std::string str = "Hello, world!";
std::string needle = "o,";
str.erase(str.find(needle));
std::cout << str << "\n";
}
#包括
#包括
int main(int argc,char*argv[]){
std::string str=“你好,世界!”;
std::string needle=“o,”;
str.erase(str.find(针));
std::cout似乎要删除str.find(a[1])之后的所有内容。在这种情况下,可以忽略第二个参数
#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
std::string str = "Hello, world!";
std::string needle = "o,";
str.erase(str.find(needle));
std::cout << str << "\n";
}
#包括
#包括
int main(int argc,char*argv[]){
std::string str=“你好,世界!”;
std::string needle=“o,”;
str.erase(str.find(针));
std::cout如果未找到字符串,find
返回string::npos
,则您的代码将无法工作,并将出现运行时错误。请参阅此错误:
所以最好写下:
size_t pos = str.find(a[1]);
if ( pos != std::string::npos)
str.erase(pos); //str.size() is not needed!
现在,这不会给出错误:如果找不到字符串,find
返回string::npos
,那么您的代码将无法工作,并将给出运行时错误。请参阅此错误:
所以最好写下:
size_t pos = str.find(a[1]);
if ( pos != std::string::npos)
str.erase(pos); //str.size() is not needed!
现在这没有给出错误:为什么您认为这不起作用?如果您有错误,请将其与相关代码一起发布。理想情况下,这是一个编译、运行和复制错误的最小代码示例。为什么您认为这不起作用?如果您有错误,请将其与相关代码一起发布。理想情况下这是一个编译、运行和再现错误的最小代码示例。