Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading