OneBite.Dev - Coding blog in a bite size

find the position of the last occurrence of a substring in a string in C

Code snippet on how to find the position of the last occurrence of a substring in a string in C

  char *strrstr(const char *haystack, const char *needle)
  {
     const char *last = NULL;
     const char *current = strstr(haystack, needle);

     /* Iterate through all occurrences of needle in haystack */
     while (current != NULL)
     {
        last = current;
        current = strstr(current + 1, needle);
     }

     return (char *)last;
  }

This code finds the position of the last occurrence of a substring in a string in C. It takes two parameters: haystack and needle. The haystack is the string in which the substring needs to be found and the needle is the substring that needs to be found. Firstly, the last pointer is initialized to NULL, then a current pointer is created and set to the result of the strstr() function, which searches a string for a given substring. The while loop iterates through each occurrence of the needle in haystack. Every time it discovers a needle occurrence, it sets last to the same value as current and then searches for the next occurrence, moving the current pointer to start from the position of the previous needle occurrence plus one. When the loop is finished, it returns the pointer last.

c