I have a word count program in C that excludes special characters and number digits:
int main(){
char str[100];
int i, j = 0;
int len;
char choice;
do {
printf("Enter String: ");
fgets(str, sizeof(str), stdin);
len = strlen(str);
for (i = 0; i < len; i++) {
if((str[i] >= 'A' && str[i] <= 'Z') ||
(str[i] >= 'a' && str[i] <= 'z')) //checks if its upper or lowercase {
if (str[i] != ' ' && (str[i + 1] == ' ' || str[i + 1] == '\0'))//checks if the current character is a space and also the end of the string{
j++;
}
}
}
printf("Word count: %d\n", j);
printf ("Try again?(Y/N): ");
scanf (" %c", &choice);
getchar ();//use to clear input buffer
} while (choice == 'y' || choice == 'Y');
return 0;
}
But it doesn't count the first string after a whitespace, and seems to get a bit messy as I go on the loop.
I tried changing the values of the array, the loop, and also tried to ask AI what I've missed, but the suggestions didn't really work.
output:
Enter String: i
Word count: 0
Try again? (Y/N): Y
Enter String: i have 3 Apples
Word count: 2
Try again? (Y/N): Y
Enter String: hello WORLD
Word count: 3
Try again? (Y/N): hello world