版权声明:由陈庚汝编辑 https://blog.csdn.net/ChenGengru/article/details/83864879
输入一行字符,统计其中有多少个单词,要求每个单词之间用空格分开,且最后字符不能为空格。
这个题设限制太多,先完成,在做一些拓展。
第一次代码:
#include<stdio.h>
#include<stdlib.h>
/* 字符数组的应用 */
/* written by Chen Gengru */
/* updated on 2018-11-8 */
int main()
{
char cString[100]; /* 定义保存字符串的数组 */
int iIndex, iWord = 1;
char cBlank; /* 数组字符串 */
gets(cString); /* 输入字符串 */
if (cString[0] == '\n') /* 判断字符串为空的情况 */
{
printf("There is no char\n");
}
else if (cString[0] == ' ') /* 判断第一个字符为空格的情况 */
{
printf("The first char is just a blank\n");
}
else
{
for (iIndex = 0; cString[iIndex] != '\0'; iIndex++)
{
cBlank = cString[iIndex];
if (cBlank == ' ') /* 每输入一个空格单词数加1 */
{
iWord++;
}
}
if (iWord == 1)
{
printf("There is 1 word.\n");
}
else
{
printf("There are %d words\n", iWord);
}
}
return 0;
}
测试结果:
1,输入’I LOVE CHINA’:
2,首位输入空格:
3,首位输入回车:
?!怎么回事?原来在输入回车的时候,cString[0]应该为\0而不是\n。
更改:
#include<stdio.h>
#include<stdlib.h>
/* 字符数组的应用 */
/* written by Chen Gengru */
/* updated on 2018-11-8 */
int main()
{
char cString[100]; /* 定义保存字符串的数组 */
int iIndex, iWord = 1;
char cBlank; /* 数组字符串 */
gets(cString); /* 输入字符串 */
if (cString[0] == '\0') /* 判断字符串为空的情况 */
{
printf("There is no char\n");
}
else if (cString[0] == ' ') /* 判断第一个字符为空格的情况 */
{
printf("The first char is just a blank\n");
}
else
{
for (iIndex = 0; cString[iIndex] != '\0'; iIndex++)
{
cBlank = cString[iIndex];
if (cBlank == ' ') /* 每输入一个空格单词数加1 */
{
iWord++;
}
}
if (iWord == 1)
{
printf("There is 1 word.\n");
}
else
{
printf("There are %d words\n", iWord);
}
}
return 0;
}
成功。
思考:能不能不管开头输入空格还是回车,结尾能不能输空格,或者如果手抖在打单词的时候连续输入了两个空格,都可以直接输出正确单词个数?
关键在于:连续输入空格和首末输入的判断。其实也蛮好解决的。
代码:
#include<stdio.h>
#include<stdlib.h>
/* 字符数组的应用 */
/* written by Chen Gengru */
/* updated on 2018-11-8 */
int main()
{
char cString[100]; /* 定义保存字符串的数组 */
int iIndex, iWord = 0;
char cBlank; /* 数组字符串 */
gets(cString); /* 输入字符串 */
for (iIndex = 0; cString[iIndex] != '\0'; iIndex++)
{
cBlank = cString[iIndex];
if (cBlank == ' ') /* 每输入一个空格单词数加1 */
{
iWord++;
}
if (cString[iIndex] == ' ' && cString[iIndex-1] == ' ')
{
iWord--; /* 若连续输入空格,只记作一次 */
}
if (cString[iIndex] == ' ' && cString[iIndex+1] == '\0')
{
iWord--; /*
}
}
if (cString[0] == ' ') /* 判断开头是否是空格 */
{
iWord--;
}
iWord++; /* iWord初始值为0,故最后要加1 */
printf("number of words:%d\n", iWord);
return 0;
}
成功!