提问人:gsistelos 提问时间:9/7/2023 更新时间:9/7/2023 访问量:92
在区域中查找子字符串
find a substring in a range
问:
我尝试使用 string::find 方法在范围内查找子字符串,该字符串在范围内,但其返回 NPO
法典:
std::cout << "find: \"" << find << "\"" << std::endl;
std::cout << "headerEnd: " << this->_headerEnd << std::endl;
size_t startPos = this->_request.find(find.c_str(), 0);
std::cout << "startPos1: " << startPos << std::endl;
startPos = this->_request.find(find.c_str(), 0, this->_headerEnd);
std::cout << "startPos2: " << startPos << std::endl;
输出:
find: "Content-Type: "
headerEnd: 641
startPos1: 294
startPos2: 18446744073709551615
根据我的理解,第二个查找应该返回相同的值,因为它从 0 到 641 (headerEnd) 进行搜索,并且字符串位于 294,长度仅为 14 个字符
那么,为什么它要返回NPO?我尝试从 C++98 更改为 C++11,但仍然给我相同的输出
答:
1赞
LiuYuan
9/7/2023
#1
您误解了第二个函数的行为。请阅读 doc(2)。
该函数真正要做的是在调用函数 start from 的对象中找到 [s, s + count] 范围内的子字符串。下面是一个小例子:s
pos
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "abc123bcd";
cout << (str.find("123321", 0, 3)) << std::endl;
}
输出 . 表示,找到范围 [0, 3] 的子字符串,该子字符串位于 中。3
str.find("123321", 0, 3)
123321
123
str
在您的代码中,这意味着搜索 长度为 的子字符串,即 641,远远大于实际大小 14。这会使您的搜索失败。find.c_str()
this->_headerEnd
this->_request
评论
0赞
LiuYuan
9/7/2023
@gsistelos 使用打印来查找错误是一种非常低效的方法。阅读文档或使用调试器通常是更好的选择。你也可以像这样问stackoverflow社区
0赞
gsistelos
9/7/2023
谢谢,这样实际上更有意义,我可以使用查找并检查是否(startPos > this->_headerEnd)
0赞
LiuYuan
9/7/2023
@gsistelos通常是更好的选择,无论是在可读性还是安全性方面if (startPos == npos)
0赞
gsistelos
9/7/2023
检查它是否在我想要的范围内(0 到 this->_headerEnd),意味着它没有找到或在范围之后找到,所以我可以在那里处理这种情况if (startPos >= this->_headerEnd)
0赞
LiuYuan
9/7/2023
@gsistelos 是的,我知道你的意思。如果未找到,则返回 ,定义为静态 constexpr size_type npos = size_type(-1);
。如果您使用上面显示的表达式,则要求寄存器将有符号整数解析为无符号整数,然后将其与字符串大小进行比较。虽然它实际上适用于解析,因为无符号整数是最大值,但它仍然有点奇怪,我无法判断在某些特殊情况下是否会出错find
npos
-1
评论