Is there a reverse function for strstr

后端 未结 17 2225
闹比i
闹比i 2020-12-18 18:28

I am trying to find a similar function to strstr that searches a substring starting from the end towards the beginning of the string.

相关标签:
17条回答
  • 2020-12-18 19:08

    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

    0 讨论(0)
  • 2020-12-18 19:09

    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.

    0 讨论(0)
  • 2020-12-18 19:16

    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.

    0 讨论(0)
  • 2020-12-18 19:17

    Here is one. Testing it is an exercise I'll leave to you :)

    0 讨论(0)
  • 2020-12-18 19:18
    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;    
    }
    
    0 讨论(0)
  • 2020-12-18 19:20

    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;
    }
    
    0 讨论(0)
提交回复
热议问题