为什么string.find(“”)找不到“”?

时间:2015-10-20 06:03:28

标签: html c++ string find

我的程序完全正常,但找不到</a>。 它可以找到一切,例如由于某种原因,它可以找到</b></i></head>等但不是</a>

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string HTML_text;
    getline(cin, HTML_text, '\t');
    cout << endl << "Printing test!";

    // replacing hyperlink
    string sub_string;
    int index_begin = HTML_text.find("<a href=") + 8;
    string helper = HTML_text.substr(index_begin, HTML_text.size());
    int index_end = helper.find(">");
    helper.clear();
    sub_string = HTML_text.substr(index_begin, index_end);
    //substring is made

    index_begin = HTML_text.find(">", index_begin) + 1;
    index_end = HTML_text.find("</a>");       //HERE IS THE PROBLEM
    helper = HTML_text.substr(index_begin, index_end);
    cout << "\n\nPrinting helper!\n";
    cout << helper << endl << endl;

    HTML_text.erase(index_begin, index_end);

    HTML_text.insert(index_begin, sub_string);

    cout << endl << "Printing results!";
    cout << endl << endl << HTML_text << endl << endl;
}

我正在使用的HTML.text是这样的:

<html>
<head>
text to be deleted
</head>
<body>
Hi there!
<b>some bold text</b>
<i>italic</i>
<a href=www.abc.com>link text</a>
</body>
</html>      //tab and then enter

1 个答案:

答案 0 :(得分:1)

问题不是您认为的问题:</a>正常工作并找到字符串中包含index_end的位置:如果您观察值{{{}},您可以在调试器中轻松查看1}}。如果找不到</a>index_end将等于std::string::npos),但它是123,而index_begin是114。

让我们来看看std::string.erase()

的文档
string& erase (size_t pos = 0, size_t len = npos);

擦除方法的签名有两个参数,位置和代码假设的长度,第二个参数是结束位置(同样也是如此,{{3 }})。

这不是一个大问题,可以轻松修复,因为我们可以简单地计算长度

length = end_position - start_position;

所以你的固定代码是:

#include <iostream>
#include <string>

using namespace std;

int main()
{
  string HTML_text;
  getline(cin, HTML_text, '\t');
  cout << endl << "Printing test!";

  // replacing hyperlink
  string sub_string;
  int index_begin = HTML_text.find("<a href=") + 8;
  string helper = HTML_text.substr(index_begin);
  int index_end = helper.find(">");
  helper.clear();
  sub_string = HTML_text.substr(index_begin, index_end);
  //substring is made

  index_begin = HTML_text.find(">", index_begin) + 1;
  index_end = HTML_text.find("</a>");
  helper = HTML_text.substr(index_begin, index_end - index_begin);
  cout << "\n\nPrinting helper!\n";
  cout << helper << endl << endl;

  HTML_text.erase(index_begin, index_end - index_begin);

  HTML_text.insert(index_begin, sub_string);

  cout << endl << "Printing results!";
  cout << endl << endl << HTML_text << endl << endl;
}

正如您所期望的那样输出:

Printing test!

Printing helper!
link text


Printing results!

<html>
<head>
text to be deleted
</head>
<body>
Hi there!
<b>some bold text</b>
<i>italic</i>
<a href=www.abc.com>www.abc.com</a>
</body>
</html>