diff options
author | zlg <zlg@zlg.space> | 2013-09-02 07:11:07 -0500 |
---|---|---|
committer | zlg <zlg@zlg.space> | 2013-09-02 07:11:07 -0500 |
commit | 5d4b543ae9fbdaf7b86cbbd2b652808ce282c91f (patch) | |
tree | f0eb1cedd229464fd16f4505b27608037c21e210 | |
parent | Solve Exercise 5-3: pointer-powered strcat() (diff) | |
download | knr-5d4b543ae9fbdaf7b86cbbd2b652808ce282c91f.tar.gz knr-5d4b543ae9fbdaf7b86cbbd2b652808ce282c91f.tar.bz2 knr-5d4b543ae9fbdaf7b86cbbd2b652808ce282c91f.tar.xz knr-5d4b543ae9fbdaf7b86cbbd2b652808ce282c91f.zip |
Solve Exercise 5-4: strend()
Detailed answers below the question will only occur now if I cannot
explain myself well enough in code and nearby comments. I'm looking
to learn how to write better comments so there's less need for prose.
-rw-r--r-- | ch5/5-04_strend.c | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/ch5/5-04_strend.c b/ch5/5-04_strend.c new file mode 100644 index 0000000..8fec2a2 --- /dev/null +++ b/ch5/5-04_strend.c @@ -0,0 +1,37 @@ +#include <stdio.h> +#include <string.h> + +/* The C Programming Language: 2nd Edition + * + * 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. + * + * Answer: Check from the end of the string! + */ + +int strend(char *, char *); + +int main() { + char *foo = "kekt"; + char *bar = "buckets of kekt"; + printf("%d\n", strend(bar, foo)); // should output 1 + foo = "missile"; + bar = "Did you see those missiles?!"; + printf("%d\n", strend(bar, foo)); // should output 0 + return 0; +} + +int strend(char *s, char *t) { + // Go to the end of s + while (*s != '\0') { + s++; + } + // back up s by however long t is + s -= strlen(t); + // Check to be sure the rest of the string matches + for (; *s == *t && *s != '\0' && *t != '\0'; s++, t++); + if (*s == '\0' && *t == '\0') { + return 1; + } + return 0; +} |