aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-01-22 12:56:35 +0100
committerAbigail <abigail@abigail.be>2021-01-22 13:03:07 +0100
commit4e4ef99b1f7257e4fc10075bdc03196ed31cbdee (patch)
tree1865d27590e2f4bbd9657720aad4f5fd19a5f8b6
parent5c43277e4f2fd1b90d3a51f140f3f4be04e5a06c (diff)
downloadperlweeklychallenge-club-4e4ef99b1f7257e4fc10075bdc03196ed31cbdee.tar.gz
perlweeklychallenge-club-4e4ef99b1f7257e4fc10075bdc03196ed31cbdee.tar.bz2
perlweeklychallenge-club-4e4ef99b1f7257e4fc10075bdc03196ed31cbdee.zip
We only need one pointer.
There's no need for a different pointer when searching for the beginning of the word, nor do we need strcpy to extract words before printing it. Instead, we set the first white space after a word to '\0', walk the pointer to the beginning of the word, then print it.
-rw-r--r--challenge-096/abigail/c/ch-1.c42
1 files changed, 14 insertions, 28 deletions
diff --git a/challenge-096/abigail/c/ch-1.c b/challenge-096/abigail/c/ch-1.c
index 36ec37d5fb..b01e726173 100644
--- a/challenge-096/abigail/c/ch-1.c
+++ b/challenge-096/abigail/c/ch-1.c
@@ -8,63 +8,49 @@
# 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;
+ size_t ptr;
- while ((strlen = getline (&line, &len, stdin)) != -1) {
- char * line_ptr = line;
- size_t end = strlen;
- size_t begin;
+ while ((ptr = getline (&line, &len, stdin)) != -1) {
size_t output = 0;
- while (end > 0) {
+ while (ptr > 0) {
/*
* Skip tailing whitespace
*/
- while (end > 0 && isspace (line [end - 1])) {
- end --;
+ while (ptr > 0 && isspace (line [ptr - 1])) {
+ ptr --;
}
/*
- * 'end' now just after the end of a word, or
+ * 'ptr' is 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) {
+ if (ptr <= 0) {
break;
}
/*
- * Find the beginning of a word
+ * Terminate the string just after the newly found word
*/
- begin = end - 1;
- while (begin > 0 && !isspace (line [begin - 1])) {
- begin --;
- }
+ line [ptr] = '\0';
/*
- * Extract the word out of the string: allocate memory,
- * and copy the right part of the input.
+ * Find the beginning of that word
*/
- char * word;
- if ((word = malloc ((end - begin + 1) * sizeof (char))) == NULL) {
- fprintf (stderr, "Out of memory\n");
- exit (1);
+ while (ptr > 0 && !isspace (line [ptr - 1])) {
+ ptr --;
}
- stpncpy (word, line + begin, end - begin);
/*
- * Print the string, prepended (except the first printed word)
+ * Print the word, prepended (except the first printed word)
* by a space.
*/
- printf ("%s%s", output ++ ? " " : "", word);
-
- end = begin;
+ printf ("%s%s", output ++ ? " " : "", &line [ptr]);
}
printf ("\n");
}