From 5d4b543ae9fbdaf7b86cbbd2b652808ce282c91f Mon Sep 17 00:00:00 2001
From: zlg <zlg@zlg.space>
Date: Mon, 2 Sep 2013 07:11:07 -0500
Subject: 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.
---
 ch5/5-04_strend.c | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
 create mode 100644 ch5/5-04_strend.c

(limited to 'ch5')

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;
+}
-- 
cgit v1.2.3-54-g00ecf