aboutsummaryrefslogtreecommitdiff
path: root/challenge-096/abigail
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-01-18 15:10:35 +0100
committerAbigail <abigail@abigail.be>2021-01-18 15:10:35 +0100
commit6be85bd8cd6960a0fd063e67b78f88b39df528e9 (patch)
treeefa0bf18e2063ff21d7b61183e06d42521ac9765 /challenge-096/abigail
parentb6b448564c1d62f1d4c623b9bce5f8a9f8d8b652 (diff)
downloadperlweeklychallenge-club-6be85bd8cd6960a0fd063e67b78f88b39df528e9.tar.gz
perlweeklychallenge-club-6be85bd8cd6960a0fd063e67b78f88b39df528e9.tar.bz2
perlweeklychallenge-club-6be85bd8cd6960a0fd063e67b78f88b39df528e9.zip
C solution for week 96/part 1
Diffstat (limited to 'challenge-096/abigail')
-rw-r--r--challenge-096/abigail/README.md1
-rw-r--r--challenge-096/abigail/c/ch-1.c66
2 files changed, 67 insertions, 0 deletions
diff --git a/challenge-096/abigail/README.md b/challenge-096/abigail/README.md
index c45d495eb6..ee7bed56c2 100644
--- a/challenge-096/abigail/README.md
+++ b/challenge-096/abigail/README.md
@@ -20,6 +20,7 @@ Output: "family same the of part are Raku and Perl"
~~~~
### Solutions
+* [C](c/ch-1.c)
* [AWK](awk/ch-1.awk)
* [Node.js](node/ch-1.js)
* [Perl](perl/ch-1.pl)
diff --git a/challenge-096/abigail/c/ch-1.c b/challenge-096/abigail/c/ch-1.c
new file mode 100644
index 0000000000..22ebafd404
--- /dev/null
+++ b/challenge-096/abigail/c/ch-1.c
@@ -0,0 +1,66 @@
+# include <stdlib.h>
+# include <stdio.h>
+# include <string.h>
+# include <ctype.h>
+
+int main (void) {
+ char * line = NULL;
+ size_t len = 0;
+ size_t strlen;
+
+ while ((strlen = getline (&line, &len, stdin)) != -1) {
+ char * line_ptr = line;
+ size_t end = strlen;
+ size_t begin;
+ size_t output = 0;
+ while (end > 0) {
+ /*
+ * Skip tailing whitespace
+ */
+ while (end > 0 && isspace (line [end - 1])) {
+ end --;
+ }
+
+ /*
+ * 'end' now just after the end of a word, or
+ * at the beginning of the string; if the latter,
+ * there is nothing left to print.
+ */
+
+ if (end <= 0) {
+ break;
+ }
+
+ /*
+ * Find the beginning of a word
+ */
+ begin = end - 1;
+ while (begin > 0 && !isspace (line [begin - 1])) {
+ begin --;
+ }
+
+ /*
+ * Extract the word out of the string: allocate memory,
+ * and copy the right part of the input.
+ */
+ char * word;
+ if ((word = malloc ((end - begin + 1) * sizeof (char))) == NULL) {
+ fprintf (stderr, "Out of memory\n");
+ exit (1);
+ }
+ stpncpy (word, line + begin, end - begin);
+
+ /*
+ * Print the string, prepended (except the first printed word)
+ * by a space.
+ */
+ printf ("%s%s", output ++ ? " " : "", word);
+
+ end = begin;
+ }
+ printf ("\n");
+ }
+ free (line);
+
+ return (0);
+}