I am trying to find a similar function to strstr
that searches a substring starting from the end towards the beginning of the string.
I don't know of one. One of the nice things about C is that if you write your own function, it's just as fast and efficient as the library ones. (This is totally not the case in many other languages.)
You could reverse the string and the substring, and then search.
Finally, the other thing people often do when the string library isn't good enough is to move to regular expressions.
Ok, I wrote both reverse()
and rstrstr()
, which might work if we are lucky. Get rid of __restrict
for C++. You also might want to make the parameters const
, but then you will need to cast the return value. To answer your comment question, you can get the index from the address of the substring by just substracting the original string pointer from it. OK:
#include
#include
char *reverse(const char * __restrict const s)
{
if (s == NULL)
return NULL;
size_t i, len = strlen(s);
char *r = malloc(len + 1);
for(i = 0; i < len; ++i)
r[i] = s[len - i - 1];
r[len] = 0;
return r;
}
char *rstrstr(char *__restrict s1, char *__restrict s2)
{
size_t s1len = strlen(s1);
size_t s2len = strlen(s2);
char *s;
if (s2len > s1len)
return NULL;
for (s = s1 + s1len - s2len; s >= s1; --s)
if (strncmp(s, s2, s2len) == 0)
return s;
return NULL;
}