Is there a reverse function for strstr

后端 未结 17 2226
闹比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:28

    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...

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

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

    Though non-standard, strrstr is widely supported and does exactly what you want.

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

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