Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird strstr behaviour

Tags:

c

strstr

i'm trying to find the position of substring in a string.

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

void find_str(char const* str, char const* substr) 
{
    char* pos = strstr(str, substr);
    if(pos) {
        printf("found the string '%s' in '%s' at position: %d\n", substr, str, pos - str);
    } else {
        printf("the string '%s' was not found in '%s'\n", substr, str);
    }
}

int main(int argc, char* argv[]) 
{
    char* str = "gdeasegrfdtyguhıjohhıhugfydsasdrfgthyjkjhghh";
    find_str(str, "hh");
    find_str("dhenhheme    kekekeke hhtttttttttttttttttttttttttttttttttttttttthhtttttttttttt", "hh");

    return 0;
}

Output:

found the string 'hh' in 'gdeasegrfdtyguhıjohhıhugfydsasdrfgthyjkjhghh' at position: 19

found the string 'hh' in 'dhenhheme kekekeke hhtttttttttttttttttttttttttttttttttttttttthhtttttttttttt' at position: 4

In first example it says its in the position 19. But shouldn't it say 18? Because in the second example it says 4. And it starts at the beginning of substring.

I'm confused.

like image 859
Can Vural Avatar asked Jan 12 '23 15:01

Can Vural


1 Answers

The character 'ı' is not an ASCII character, so it probably takes up two bytes.

like image 193
Some programmer dude Avatar answered Jan 14 '23 05:01

Some programmer dude