Is there a reverse function for strstr

后端 未结 17 2388
闹比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: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;
    }
    

提交回复
热议问题