繁体   English   中英

您如何使用string.erase和string.find?

[英]How do you use string.erase and string.find?

为什么我不能像这样调用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

该调用没有任何问题(假设a[1]存在并且在str中至少发现一次)

#include <iostream>
#include <string>
int main()
{
        std::string str = "Hello, world!";
        std::string a = "wwwwww";
        str.erase(str.find(a[1]), str.size());
        std::cout << str << '\n';
}

测试运行: https//ideone.com/8wibR

编辑:您的完整源代码无法检查b[1]是否在str实际找到。 如果a.find(b)大于零,则函数boolStringExists()返回1如果在大于零a IS中找不到b ,则返回的std::string::npos值将返回1

要解决此问题,同时保持其余逻辑不变,请将功能更改为

//check if string exists
bool boolStringExists(string a, string b)
{
    return a.find(b) != string::npos;
}

看来您想删除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";
}

在此示例中,我使用needle代替a[1] ,但是原理是相同的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM