我正在尝试解析一个包含一行 XML 文件的字符串。
std::string temp = "<Album>Underclass Hero</Album>";
int f = temp.find(">");
int l = temp.find("</");
std::string _line = temp.substr(f + 1, l-2);
这是我的函数代码的一部分,它实际上应该返回解析后的字符串。我所期望的是它返回 Underclass Hero。相反,我得到了Underclass Hero
(这里在 '<' 和 '/' 之间有一个空格,因为我不能把它们写在一起)。
我看了 std::string::find 好几次,它总是说它返回,如果存在,第一个匹配的第一个字符的位置。这里它给了我字符串的最后一个字符,但只在我的变量 l 中。
f 很好。
那么谁能告诉我我做错了什么?
最佳答案
第二个参数是要提取的子字符串的长度。您可以通过这种方式修复代码:
#include <string>
#include <iostream>
int main()
{
std::string temp = "<Album>Underclass Hero</Album>";
int f = temp.find(">");
int l = temp.find("</");
std::string line = temp.substr(f + 1, l - f - 1);
// ^^^^^^^^^
}
这是一个live example .
此外,请注意诸如 _line
之类的名称。根据 C++11 标准的第 17.6.4.3.2/1 段:
[...] Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
关于c++ - Xml 解析器 - 字符串::查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15840058/