我尝试使用 string::find 方法在范围内查找子字符串,该字符串在范围内,但返回 npos
代码:
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 个字符长
那么为什么它会返回 npos?我尝试从 c++98 更改为 c++11,但仍然给出相同的输出
您误解了第二个函数的行为。请阅读doc(2)。
该函数真正做的是在调用该函数的对象中从
s
开始查找范围 [s, s + count) 中 pos
的子字符串。这是一个小例子:
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "abc123bcd";
cout << (str.find("123321", 0, 3)) << std::endl;
}
输出
3
。 str.find("123321", 0, 3)
的意思是,找到123321
在[0, 3)范围内的子串,即123
中的str
。
在你的代码中,这意味着在
find.c_str()
中查找长度为this->_headerEnd
的this->_request
的子串,即641,远大于实际大小14。这使得你的搜索失败。