繁体   English   中英

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

[英]why string.find("</a>") cant find "</a>"?

除了找不到</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

问题不在你假设的地方: index_end = HTML_text.find("</a>"); 正常工作并找到包含</a>的字符串中的位置:如果您查看值index_end您可以在调试器中轻松看到。 如果找不到</a>index_end将等于std::string::npos ),但它是 123 而index_begin是 114。

我们来看看std::string.erase()的文档

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

擦除方法的签名有两个参数,位置和长度,而您的代码假定第二个参数将是结束位置(对于std::string.substr()也是如此)。

这不是什么大问题,很容易解决,因为我们可以简单地计算长度

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>

暂无
暂无

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

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