I am trying to find a similar function to strstr
that searches a substring starting from the end towards the beginning of the string.
Thanks for your answers! There is one more way which came from the MSDN forum. http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/ed0f6ef9-8911-4879-accb-b3c778a09d94
I think you can still do it using library functions.
1.Use strrev function to reverse the string.
2.Use strstr function to do whatever you want to do.
3.You can find start index (from reverse ) of the search string by subtracting start index of the search string from the length of original string.
There isn't one in the standard C library. You may be able to find one on the web, or you may have to write your own.
Here is one. Testing it is an exercise I'll leave to you :)
char* strrstr(char * _Str, const char * _SubStr)
{
const BYTE EQUAL=0;
int i=0, src_len = strlen(_Str), find_len = strlen(_SubStr),
tail_count=0;
for(i=src_len; i>-1; i--)
{
if(_Str[i] == _SubStr[0] && tail_count >= find_len)
{
if(strncmp(&_Str[i], _SubStr, find_len) == EQUAL)
{
return &_Str[i];
}
}
tail_count++;
}
return NULL;
}
Here is the most minimal simple implantation that I could come up with. Unlike other implementations of this function it avoids the initial strstr call that some other people like user3119703 had.
char * lastStrstr(const char * haystack,const char * needle){
char*temp=haystack,*before=0;
while(temp=strstr(temp,needle)) before=temp++;
return before;
}