Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if string is reverse substring

I need to write function which will check if string s2 is reverse substring of string s1, and return 1 if the condition is true. Function should be made using pointer arithmetic.

For example:

char s1[] = "abcdef";
char s2[] = "edc";

Function would return 1 because string s1 contains reverse string s2.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>
int reverseSubstring(const char *s1, const char *s2) {
  while (*s1 != '\0') {
    const char *p = s1;
    const char *q = s2;
    while (*p++ == *q++)
      if (*q == '\0')
        return 1;
    s1++;
  }
return 0;
}

int main() {
  char s1[] = "abcdef";
  char s2[] = "edc";
  printf("%d", reverseSubstring(s1, s2));
  return 0;
}

This function does the opposite. It checks if the string is substring and in my case it returns 0. It should return 1. How to modify this to work?

  • Note: it is not allowed to use functions from the string.h, stdlib.h libraries, nor the sprintf and sscanf functions from the stdio.h library. It is not allowed to create auxiliary strings or strings in function or globally.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading