Exercise 5-4 (strend - String ending in another string)
Chapter_5 Exercise_5-3 | Exercise_5-5 |
Exercise 5-4 K&R, p. 107
Exercise 5-4. Write the function strend(s,t), which returns 1 if the string t occurs at the end of the string s, and zero otherwise.
strend.c download
#include <stdio.h> // for printf(), scanf()
#define SIZE 100 // array size
int strend(char *, char *); // first string ends with the second ? 1 : 0
int main()
{
char s[SIZE*2], t[SIZE];
printf("Type a string: ");
scanf("%s", s);
printf("Type another string: ");
scanf("%s", t);
printf("\"%s\" %s \"%s\"\n", s, strend(s,t) ? "ends with" : "doesn't end with", t);
return 0;
}
int strend(char *s, char *t) // first string ends with the second ? 1 : 0
{
int lens = 0, lent = 0; // length of s, t
while (*s) {lens++, s++;}
while (*t) {lent++, t++;}
if (lens < lent) {return 0;}
while (lent-- && *s-- == *t--) {}
if (*s != *t) {return 0;}
return 1;
}
/*
gcc strend.c -o strend
./strend
Type a string: anna
Type another string: ana
"anna" doesn't end with "ana"
./strend
Type a string: ana
Type another string: anna
"ana" doesn't end with "anna"
./strend
Type a string: anna
Type another string: anna
"anna" ends with "anna"
./strend
Type a string: card
Type another string: cardboard
"card" doesn't end with "cardboard"
./strend
Type a string: cardboard
Type another string: card
"cardboard" doesn't end with "card"
./strend
Type a string: cardboard
Type another string: board
"cardboard" ends with "board"
*/
Chapter_5 Exercise_5-3 | BACK_TO_TOP | Exercise_5-5 |
Comments
Post a Comment