check if a string is a reverse substring

Slight modification to parts of your code:

const char *q = s2;

while(*q) q++; // Make q point to end of string

while (*p++ == *--q) // Decrement instead of incrementing
  if (q == s2) // If we have traversed complete substring
    return 1;

This is most likely good enough for a school task, which this most likely is. But it might be good to know that the operation q-- will invoke undefined behavior for an empty string because it will make q point to the element before the string. That can be easily fixed. Just add if(*s2 == '\0') return 1; in the beginning of the function because an empty string is a substring of every string.

For completeness, here is a full version with some small fixes and optimizations. I also took the liberty of replacing a while loop with the library function strlen even if it was forbidden in the task. After all, the while loop is described above, and strlen is easy to implement on your own.

const char *
reverseSubstring(const char *s1, const char *s2) {
    if(*s2 == '\0') return s1;

    const char *end = s2 + strlen(s2);

    while (*s1 != '\0') {
        const char *p = s1;
        const char *q = end;
         
        while (*p++ == *--q)) {
            if (q == s2) return s1;
        }
          
        s1++;
    }

    return NULL;
}

Note that I changed the return type. It returns NULL if no match is found, but if a match is found, it returns a pointer to the first match. That means it contains more information for free.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top