Skip to content

Instantly share code, notes, and snippets.

@robbieferrero
Created May 24, 2018 16:33
Show Gist options
  • Save robbieferrero/93183015b168a7a06c976a284ee4723e to your computer and use it in GitHub Desktop.
Save robbieferrero/93183015b168a7a06c976a284ee4723e to your computer and use it in GitHub Desktop.
unique words in C
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
enum { MAX_WORDS = 64, MAX_WORD_LEN = 20 };
int main(void)
{
char words[MAX_WORDS][MAX_WORD_LEN];
int count[MAX_WORDS] = { 0 };
int w = 0;
char word[MAX_WORD_LEN];
int c;
int l = 0;
while ((c = getchar()) != EOF)
{
if (isalpha(c))
{
if (l < MAX_WORD_LEN - 1)
word[l++] = c;
else
{
fprintf(stderr, "Word too long: %*s%c...\n", l, word, c);
break;
}
}
else if (l > 0)
{
word[l] = '\0';
printf("Found word <<%s>>\n", word);
assert(strlen(word) < MAX_WORD_LEN);
int found = 0;
for (int i = 0; i < w; i++)
{
if (strcmp(word, words[i]) == 0)
{
count[i]++;
found = 1;
break;
}
}
if (!found)
{
if (w >= MAX_WORDS)
{
fprintf(stderr, "Too many distinct words (%s)\n", word);
break;
}
strcpy(words[w], word);
count[w++] = 1;
}
l = 0;
}
}
for (int i = 0; i < w; i++)
printf("%3d: %s\n", count[i], words[i]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment