统计一段字符串中有多少个单词
#include<iostream>
#include<stdio.h>
using namespace std;
void main() {
//统计一段字符串中有多少个单词
//输入一行字符,统计其中有多少个单词,要求每个单词之间用空格隔开,最后的字符不能为空格
char str[100];
int i, word = 1;
char blank;
gets_s(str);//输入一行字符
if (str[0] == '\0')
cout << "There is no words";
else if (str[0] == ' ') {
cout << "there is just a blank";
}
else {
for (i = 0; str[i] != '\0'; i++) {
blank = str[i]; // 判断当前字符是否为空格
if (blank == ' ')
word++;
}
cout << "there are "<< word<<" words" << endl;
}
}
运行结果