Advertisement
cd62131

count words

May 23rd, 2019
659
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #include <ctype.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. typedef struct word word;
  6. struct word {
  7.   char *word;
  8.   int count;
  9.   word *next;
  10. };
  11. static word *word_alloc(char *w) {
  12.   word *new = calloc(1, sizeof *new);
  13.   new->word = strdup(w), new->count = 1, new->next = NULL;
  14.   return new;
  15. }
  16. static void word_free(word *p) {
  17.   if (!p) { return; }
  18.   word_free(p->next), free(p->word), free(p);
  19. }
  20. static void add_word(word **head, char *w) {
  21.   if (!*head) {
  22.     *head = word_alloc(w);
  23.     return;
  24.   }
  25.   for (word *p = *head; p; p = p->next) {
  26.     if (!strcmp(w, p->word)) {
  27.       ++p->count;
  28.       return;
  29.     }
  30.   }
  31.   word *new = word_alloc(w);
  32.   new->next = *head, *head = new;
  33. }
  34. static void input(FILE *in, word **head) {
  35.   char buf[BUFSIZ];
  36.   while (fgets(buf, BUFSIZ, in)) {
  37.     for (char *p = buf; *p; ++p) {
  38.       if (!isalpha(*p)) { *p = ' '; }
  39.       *p = tolower(*p);
  40.     }
  41.     char w[BUFSIZ];
  42.     for (char *p = buf; *p; ++p) {
  43.       if (isblank(*p)) { continue; }
  44.       if (sscanf(p, "%s", w) == 1) { add_word(head, w), p += strlen(w); }
  45.     }
  46.   }
  47. }
  48. static void show_word(word *head) {
  49.   for (word *p = head; p; p = p->next) { printf("%s %d\n", p->word, p->count); }
  50. }
  51. int main(int argc, char **argv) {
  52.   FILE *in = stdin;
  53.   if (argc == 2) { in = fopen(argv[1], "r"); }
  54.   word *head = NULL;
  55.   input(in, &head), show_word(head), word_free(head), fclose(in);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement