C Language Word Count Tutorial
You can count the number of words in a text by following these steps:
- Open the text file and read the contents.
- Iterate through the content of the file, check each character individually to see if it is a letter or a number, and if it is, add that character to a temporary string.
- When encountering characters that are not letters or numbers, check if the temporary string is empty. If it is not empty, count the word and clear the temporary string.
- Continue to traverse the text content until it is fully traversed.
- Output the final count of the words in the statistics.
Here is a simple example code:
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *file;
char ch;
char word[50];
int count = 0;
file = fopen("text.txt", "r");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}
while ((ch = fgetc(file)) != EOF) {
if (isalnum(ch)) {
strncat(word, &ch, 1);
} else {
if (strlen(word) > 0) {
count++;
word[0] = '\0';
}
}
}
if (strlen(word) > 0) {
count++;
}
printf("Total words: %d\n", count);
fclose(file);
return 0;
}
In the example code above, it is assumed that the text content to be counted is saved in a text file named “text.txt”. The code will read each character in the file one by one, and check if it is a letter or a number. If it is a letter or number, the character will be added to a temporary string “word”. When a non-letter or non-number character is encountered, the code will check if the temporary string is empty. If it is not empty, it will increment the count by one and clear the temporary string. Finally, it will output the total number of words counted.