【问题标题】:How do you use string.erase and string.find?如何使用 string.erase 和 string.find?
【发布时间】:2011-03-15 18:42:10
【问题描述】:

为什么我不能像这样在 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;
}

给出以下消息:“此应用程序已请求运行时以异常方式终止它。请联系应用程序的支持团队以获取更多信息。”

【问题讨论】:

  • 为什么你认为这不起作用?如果您有错误,请将其与相关代码一起发布。理想情况下,这是一个编译、运行和重现错误的最小代码示例。

标签: c++ string


【解决方案1】:

如果没有找到该字符串,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

【讨论】:

    【解决方案2】:

    该调用没有任何问题(假设 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 中找不到b 时返回的std::string::npos 的值大于零。

    要在保持其余逻辑不变的同时解决此问题,请将函数更改为

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

    【讨论】:

      【解决方案3】:

      您似乎想删除 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],但是原理是一样的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 2021-11-02
        • 2010-10-15
        相关资源
        最近更新 更多