MD XF MD XF - 1 month ago 8
C Question

Check if and where a substring exists

I saw this question but none of the answers were quite what I was looking for. I've tried

strstr
but it returns a pointer instead of an integer index.

I need to find if string
a
contains string
b
and if so, where it's located, kind of like the index returned by
strcmp
. Is there a function or easy way to do this in C?

For example, if
a
is "foobar" and
b
is "bar", then this function/method would return 3 because "bar" is at index 3 of "foobar".

Any help is appreciated!

Answer

You can use strstr for this, along with some pointer arithmetic.

char *result = strstr(a, b);
if (result != NULL) {
    printf("index = %tu\n", result - a);
}

Here, result points a particular number of bytes ahead of a. So if you subtract the two, that's your index.