Skip to content

Instantly share code, notes, and snippets.

@jbenner-radham
Last active April 20, 2017 00:10
Show Gist options
  • Save jbenner-radham/b8400186dccbb5f8ea85e26c35eb82a2 to your computer and use it in GitHub Desktop.
Save jbenner-radham/b8400186dccbb5f8ea85e26c35eb82a2 to your computer and use it in GitHub Desktop.
Comparing a couple different function implementations.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <string.h>
#define PENCIL_SPACE ' '
size_t paper_word_count(char *paper)
{
size_t count = 0;
char *ptr = paper;
do {
if (!*ptr) {
break;
}
if (*(ptr - 1) == '\0' && *ptr != PENCIL_SPACE) {
count += 1;
}
if (*(ptr - 1) == PENCIL_SPACE && *ptr != PENCIL_SPACE) {
count += 1;
}
} while (*(++ptr));
return count;
/*
size_t count = 0;
char *ptr = paper;
for (size_t pos = 0, len = strnlen(paper, BUFSIZ); pos < len; ++pos, ++ptr) {
if (pos == 0 && *ptr != PENCIL_SPACE) {
count += 1;
}
if (pos >= 1 && *ptr != PENCIL_SPACE && *(ptr - 1) == PENCIL_SPACE) {
count += 1;
}
}
return count;
*/
/*
size_t count = 0;
const char *delimiter = " ";
char *state = NULL;
char *word;
word = strtok_r(paper, delimiter, &state);
if (word == NULL) {
return count;
}
count += 1;
while((word = strtok_r(NULL, delimiter, &state))) {
count += 1;
}
return count;
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment