c++c++98

find a substring in a range


im trying to find a substring in a range using the string::find method, the string is in range but its returning npos

code:

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;

output:

find: "Content-Type: "
headerEnd: 641
startPos1: 294
startPos2: 18446744073709551615

from my understanding, the second find should return the same value, as it is searching from 0 to 641 (headerEnd) and the string is located at 294 being only 14 characters long

so why is it returning npos? ive tried changing from c++98 to c++11 and still gives me the same output


Solution

  • You misunderstood the behavior of the second function. Please read the doc(2).

    What the function really do is find substring of s in range [s, s + count) in the object calling the function start from pos. Here is a small example:

    #include <iostream>
    #include <string>
    
    using std::cout;
    using std::string;
    
    int main() {
      string str = "abc123bcd";
      cout << (str.find("123321", 0, 3)) << std::endl;
    }
    

    which outputs 3. str.find("123321", 0, 3) means, find the substring of 123321 of range [0, 3), which is 123 in str.

    In your code, it means search the substring of find.c_str() of length this->_headerEnd in this->_request, which is 641, far more than the real size 14. Which makes your search failed.