MD XF MD XF - 1 year ago 76
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

but it returns a pointer instead of an integer index.

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

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

Any help is appreciated!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download