Count the number of words in a line of text.

6-9 PTA counts the number of words in a line of text.

This topic requires writing a program to count the number of words in a line of characters. The so-called "word" refers to a string without spaces in a row. Each word is separated by a space, and the number of spaces can be multiple.

Input format:
input gives a line of characters.

Output format:
output the number of words in a line.

Input sample:
Let's go to room 209.
Output sample:
5

#include<stdio.h>
int main(){
    
    					     //该算法以空格为计算“单词”数量的媒介
  int i=0,j=0;
  char ch;
  while((ch=getchar())!='\n'){
    
    
    if(ch!=' ') i++;	    	//计每个字符组的字符数
    else{
    
    
      if(i>0){
    
    					//判断前面最近的一个字符组是否有字符
        j++;					//有的话字符组+1
        i=0;					//前一字符组中字符个数清零
			}
		}
  }
  if(i>0) j++;					//若最后不是以空格结束,则“单词”+1
  printf("%d",j);
  return 0;
}

If you have any better suggestions, please leave a message below. Please correct me if there is something wrong.

Guess you like

Origin blog.csdn.net/qq_51932922/article/details/112388225