C语言实现输入一行字符串,统计其单词的个数

方法一:

#include <stdio.h>
#include "string.h"
int main ( )
{
    
    
//   统计一行英文字母中所含有的单词的个数:
    printf("请输入一行英文字符串,统计其单词的个数:");
    char ch[]={
    
    };
    gets(ch);
    printf("你输入的字符串为:%s\n",ch);
    int i =0 ,count=0,word=0;
    for (; ch[i]!='\0'; i++) {
    
    
        if(ch[i]==' '){
    
    
            word=0 ;
        }else if(word==0){
    
    
            word=1;
            count++;
        }
    }
    printf("%s所含的英文单词的个数为:%d\n",ch,count);
}

在这里插入图片描述

方法二:

#include <stdio.h>
#include "string.h"
int main ( )
{
    
    
//   统计一行英文字母中所含有的单词的个数:
    printf("请输入一行英文字符串,统计其单词的个数:");
    char ch[100];
    gets(ch);
    printf("你输入的字符串为:%s\n",ch);
    int i =0 ,count=0;
    for (; ch[i]!='\0'; i++) {
    
    
        if (ch[i]==' ') {
    
    
            continue;
        }else{
    
    
            count++;
            for (; ch[i]!='\0'; i++) {
    
    
                if (ch[i]==' ') {
    
    
                    break;
                }
            }
        }
    }
    printf("所含的英文单词的个数为:%d\n",count);
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45696288/article/details/122265615