Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctype.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct word word;
- struct word {
- char *word;
- int count;
- word *next;
- };
- static word *word_alloc(char *w) {
- word *new = calloc(1, sizeof *new);
- new->word = strdup(w), new->count = 1, new->next = NULL;
- return new;
- }
- static void word_free(word *p) {
- if (!p) { return; }
- word_free(p->next), free(p->word), free(p);
- }
- static void add_word(word **head, char *w) {
- if (!*head) {
- *head = word_alloc(w);
- return;
- }
- for (word *p = *head; p; p = p->next) {
- if (!strcmp(w, p->word)) {
- ++p->count;
- return;
- }
- }
- word *new = word_alloc(w);
- new->next = *head, *head = new;
- }
- static void input(FILE *in, word **head) {
- char buf[BUFSIZ];
- while (fgets(buf, BUFSIZ, in)) {
- for (char *p = buf; *p; ++p) {
- if (!isalpha(*p)) { *p = ' '; }
- *p = tolower(*p);
- }
- char w[BUFSIZ];
- for (char *p = buf; *p; ++p) {
- if (isblank(*p)) { continue; }
- if (sscanf(p, "%s", w) == 1) { add_word(head, w), p += strlen(w); }
- }
- }
- }
- static void show_word(word *head) {
- for (word *p = head; p; p = p->next) { printf("%s %d\n", p->word, p->count); }
- }
- int main(int argc, char **argv) {
- FILE *in = stdin;
- if (argc == 2) { in = fopen(argv[1], "r"); }
- word *head = NULL;
- input(in, &head), show_word(head), word_free(head), fclose(in);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement