I am trying to find a similar function to strstr
that searches a substring starting from the end towards the beginning of the string.
Long story short:
Nope - there is no function in the C-library that does what you need..
But as others have pointed out: It's not rocket-science to write such a function...
One possible, if not entirely elegant, implementation might look like:
#include "string.h"
const char* rstrstr(const char* haystack, const char* needle)
{
int needle_length = strlen(needle);
const char* haystack_end = haystack + strlen(haystack) - needle_length;
const char* p;
size_t i;
for(p = haystack_end; p >= haystack; --p)
{
for(i = 0; i < needle_length; ++i) {
if(p[i] != needle[i])
goto next;
}
return p;
next:;
}
return 0;
}
Though non-standard, strrstr is widely supported and does exactly what you want.
char * strrstr(char *_Str, char *_SubStr){
char *returnPointer, *p;
//find 1st occurence. if not found, return NULL
if ( (p=strstr(_Str, _SubStr))==NULL)
return NULL;
//loop around until no more occurences
do{
returnPointer=p;
++p;
}while(p=strstr(p, _SubStr));
return returnPointer;
}
You can use standard algorithm std::find_end for this purpose. For example
char s[] = "What is the last word last";
char t[] = "last";
std::cout << std::find_end( s, s + sizeof( s ) - 1, t, t + sizeof( t ) -1 )
<< std::endl;