string - Program C count words (excluding numbers) -
i have come across lot of counting words examples (like 1 in link below):
counting words in string - c programming
if(str[i]==' ') { i++; }
and digit is:
if(str[i]>='0' && str[i]<='9') { i++; }
but if input 'i have 12 apples.' , want output show "word count = 3"?
assuming don't have words contain alphanumeric combinations, "foo12", combine code snippets, this:
#include <stdio.h> #include <string.h> int main(void) { char str[] = "bex 67 rep"; int len = strlen(str); int count = 0, = 0; while(str[i] != '\0') { if(str[i] == ' ') { if(i + 1 < len && ! (str[i + 1] >= '0' && str[i + 1] <= '9') && str[i + 1] != ' ') count++; } i++; } printf("word count = %d\n", count + 1); // word count = 2 return 0; }
where loop on every character of string, , when find whitespace, check - if not @ last character of string - if next character not digit or whitespace. if that's case, can assume whitespace encountered precedended of word, incease count
.
notice senteces not start whitespace (which assumption answer), number of words 1 more count
.
in real life, use strtok()
, check every token validity, since that's approach demonstration , should considered bad approach.
Comments
Post a Comment