题:输入一行字符,统计其中有多少个单词,单词间用空格隔开(注:字母间夹数字不算单词)
我的答案:
#include<stdio.h>
#include<string.h>
int main()
{
int i, num = 0, word = 0;
char str[100], c;
printf("请输入字符串str:\n");
gets_s(str,100);
for (i = 0; (c = str[i]) != '\0'; i++)
{
if (c == ' ')
word = 0;
else if (word == 0)
{
if (c >= 65 && c <= 90 || c >= 97 && c <= 122)
{
if (str[i + 1] >= '0'&&str[i + 1] <= '9')
word = 0;
else
word = 1;
num++;
}
}
}
printf("字符串共有%d个单词\n", num);
return 0;
}
运行结果:
求解救~~
我的答案:
#include<stdio.h>
#include<string.h>
int main()
{
int i, num = 0, word = 0;
char str[100], c;
printf("请输入字符串str:\n");
gets_s(str,100);
for (i = 0; (c = str[i]) != '\0'; i++)
{
if (c == ' ')
word = 0;
else if (word == 0)
{
if (c >= 65 && c <= 90 || c >= 97 && c <= 122)
{
if (str[i + 1] >= '0'&&str[i + 1] <= '9')
word = 0;
else
word = 1;
num++;
}
}
}
printf("字符串共有%d个单词\n", num);
return 0;
}
运行结果:
求解救~~