In C, there is a way to know when the end of string is reached. Is there a way to know the start when iterating backwards?

StackOverflow https://stackoverflow.com/questions/3948727

  •  08-10-2019
  •  | 
  •  

Question

I'm doing K&R Exercise 5-4 (p107).

Write the function strend(s,t) , which returns 1 if the string t occurs at the end of the string s, and zero otherwise.

I figured the best way to do this was to...

  • increment both pointers to the end
  • count backwards through both strings whilst each char matches
  • return 1 if we had finished counting to the beginning of the second string

So here is what I have...

int strend(const char *str1, const char *str2) {
   int i = 0; 
   while (*str1++ != '\0');

   while (*str2++ != '\0') {
      i++;
   }
   i++;

   while (*str2-- == *str1-- && i > 0) {
     i--;
   }

   return (i == 0);
}

As you can see, I used a counter to tell when I had arrived at the beginning of the second string.

Is there any other loop I can use without a counter to tell when we have arrived at the start of the string (similar to looking for \0 for the end of a string)?

Thanks.

Update

Didn't think to use pointers - I'm still learning and forgetting a few things!

I came up with this...

int strend(const char *str1, const char *str2) {
   char *start = str2; 
   while (*str1++ != '\0');

   while (*str2++ != '\0');

   while (*str2-- == *str1--) {
     if (str2 == start) {
         return 1;
     }
   }

   return 0;
}
Was it helpful?

Solution

Check for matching pointers?

OTHER TIPS

Compare the address of the current character to the original string pointer? If they match, then the current character must be the first one and thus the start of the string.

Are you allowed to use standard C functions? If so, you can use strlen() to get the length of each string.

E.G,

int lenS = strlen(s);
int lenT = strlen(t);

for (int i = 0; i < lenT; ++i) {
  if (s[lenS - i] != t[lenT - i])
    return 0;
}

return 1;

There is no indicator at the beginning of C strings that identify that is where the string begins. You have to keep some reference to the beginning of the string, like making a copy of the pointer str1.

Also, for this exercise, you do not have to do it with backward scanning. You can do it with using forward scanning and there are certain checks you can make to see if it's worthwhile to even bother seeing if str2 is in str1.

if you're allowed to use string functions:

int strend(char *s, char *t)
{
    char *st = s + strlen(s) - strlen(t);
    if (st < s) return 0;
    if (!strcmp(st,t)) return 1;
    return 0;
}

Even better by tia (comments):

int strend(char *s, char *t)
{
    char *st = s + strlen(s) - strlen(t);
    if (st >= s) return !(strcmp(st,t)); else return 0

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top