the program i've written counts the number of words in a string entered from the keyboard (it works).
if someone could, please tell me if there is a better way to do it or how i can improve my code.
Code:
/* header: # of words
notes: this program counts the number of words in a string.
- a word is a sequence of consecutive letters
*/
#include <stdio.h>
#include <string.h>
int nwords(int, char []);
int ctest(char, int);
int main() {
char line[100];
// get string
printf("Enter a string: ");
fgets(line, sizeof(line), stdin);
// get number of words
printf("number of words is %d", nwords(strlen(line)-1, line));
while (getchar() != '\n') ;
return 0;
}
/* name: words counter
parameters: length = length of string, line[] = string array
return: the number of words in string
note: character excludes tab, space, return, and null
*/
int nwords(int length, char line[]) {
int x = 0; // position of character in string- starts from 0
int fchar; // position of first character
int lchar; // position of last character
int letters = 0; // number of letters in sequence from fchar to lchar
int words = 0; // number of words counter
/* in line if position of last consecutive character minus position of first character
plus 1 equals the number of letters in sequence the sequence of characters is a word.
example : what happens : word
hello : fchar = 0; lchar = 4; letters = 5; lchar-fchar+1=letters yes
yes : fchar = 1; lchar = 3; letters = 3; lchar-fchar+1=letters yes
hello yes : fchar = 0; lchar = 4; letters = 5; lchar-fchar+1=letters yes
fchar = 6; lchar = 8; letters = 3; lchar-fchar+1=letters yes */
for ( x; x < length; ++x) {
if ( ctest(line[x], 3) ) { // if it isn't a tab, space, return key and NULL
fchar = x; // sets position of "first character"
if ( ctest(line[x], 1) ) ++letters; // if it is a letter, letter increments
for ( x+1; x < length; ++x) { // checks string after the "first character"
if ( ctest(line[x+1], 2) ) { // if it is a tab, space, return key or NULL, sets position of "last character" and break out of loop
lchar = x;
}
else if ( ctest(line[x+1], 1) ) { // if it is a letter, letter increments and goes to top
++letters;
continue;
}
else continue;
break;
}
}
if (lchar-fchar + 1 == letters) ++words; // if it is a word, word increments
letters = 0; // reset letter to zero - important
}
return (words);
}
/* name: character test
parameters: character = a character, consider = a number (1-3)
return: zero or 1
*/
int ctest(char character, int consider) {
switch (consider) {
case 1: // if it is a character
if ((character >= 'a' && character <='z') || (character >= 'A' && character <='Z')) return 1;
break;
case 2: // if it is a tab, space, return key or NULL
if (character == '\t' || character == ' ' || character == '\n' || character == '\0') return 1;
break;
case 3: // if it isn't a tab, space, return key and NULL
if (character != '\t' && character != ' ' && character != '\n' && character != '\0') return 1;
break;
}
return 0;
}