c++ - 你如何使用 string.erase 和 string.find?

标签 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]={"<!--...-->","<!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/

相关文章:

c# - Eigen 点到平面算法,返回四元数?

使用 atoi/sprintf 将整数转换为字符串

c# - 最佳实践 - 将字符串的第一个字符转换为小写

c++ - libjpeg:解压缩和裁剪

c++ less 运算符重载,用什么方法?

具有冲突处理的 C++ 哈希表实现

c++ - 将 std::distance 的结果与无符号类型进行比较

c++ - 通过 string::insert 插入 char 时出错

将 snake_case 更改为 PascalCase 的 Javascript 方法

Python 在字符串开头匹配 '.\'