Home > OS >  How to count the length of each word in a string of characters
How to count the length of each word in a string of characters

Time:10-27

I'm a beginner programmer and im trying to solve some exercises and i needed some help with one of them. The exercise goes like this:

We need to input a string of characters , read it and print out the length of each word.

This is what i did

int main()
{
char str[N 1 1];
int i=0;
int pos=0;
int wordlen=0;
int word[60]={0,};
printf("Please enter the string of characters: ");
gets(str);
while(i<strlen(str))
{
    if(!isalpha(str[i]))
    {
        wordlen=0;
        i  ;
    }
    if(isalpha(str[i]))
    {
        wordlen  ;
        i  ;
        pos=i;
    }
    word[pos]=wordlen;
    wordlen=0;;
    i  ;
}
for(i=0;i<20;i  )
{
    if(word[i]==0) // here im just trying to find a way to avoid printing 0's but you can ignore it if you want
        {break;}
    else
        printf("%d ",word[i]);
}
  return 0;
}

The problem is that when i try to compile it for example: I input "hi hi hi" its supposed to print 2 2 2 but instead it's printing nothing.

Can i ask for some help?

CodePudding user response:

I failed to follow OP's logic.

Perhaps begin again?

End-of-word

To "count the length of each word", code needs to identify the end of a word and when to print.

Detecting a non-letter and the current word length > 0 indicates the prior character was the end of a word. Note that every C string ends with a non-letter: '\0', so let us iterate on that too to insure loop ends on a final non-letter.

int word_length = 0;
int strlength = strlen(str);  // Call strlen() only once
while (i <= strlength) {
  if (isalpha(s[i])) {
    word_length  ;
  } else {
    if (word_length > 0) {
      printf("%d ", word_length); 
      word_length = 0;
    }
  }
}
printf("\n"); 

gets()

gets() is no longer in the C library for 10 years as it is prone to over-run. Do not use it.

we are supposed to use gets. is unfortunate and implies OP’s instruction is out-of-date. Instead, research fgets() and maybe better instruction material.

Advanced

is...() better called as isalpha((unsigned char) s[i]) to handle s[i] < 0.

In general, better to use size_t than int for string sizing and indexing as the length may exceed INT_MAX. That is not likely to happen with OP's testing here.

  •  Tags:  
  • c
  • Related