Search code examples
c++findhexstdstring

std::string::find returns wrong answer


There are some posts concerning std::string::find (like this one here and this one too) but I have a somewhat different situation:

#include <string>
#include <stdio.h>

int main(int argc, char **argv)
{
    std::string haystack = "ab\\x10c\200\\x00\\x00\\x00\\x00";
    std::string needle   = "\\x00";

    printf("first index is %d\n",(int) haystack.find(needle));

    return 0;
}

According to the values I'm wondering why 8 is returned:

I guess "\200" is counted as 1 character (?) Can I make find treat "\\x10" as 1 character too?


Solution

  • All works properly

    +---+---+---+---+---+---+---+------+---+---+---+---+
    | a | b | \ | x | 1 | 0 | c | \200 | \ | x | 0 | 0 |
    +---+---+---+---+---+---+---+------+---+---+---+---+
    | 0 | 1 | 2 | 3 | 4 | 5 | 6 |   7  | 8 |   |   |   |
    +---+---+---+---+---+---+---+------+---+---+---+---+
    

    \\ becomes one char \. It seems you wanted \xNN with one \.

    Even if you replace \\ with \ in the literal string, it will not work, since the first \x00 will be treated as terminating zero and other chars after it will be ignored. I guess that the initialization of strings should be like below:

    std::string haystack = {'a', 'b', '\x10', 'c', '\200', '\x00', '\x00', '\x00', '\x00'};
    std::string needle   = {'\x00'};
    

    The program will output 5.