版权声明:转载请声明 作者:SpacePioneer https://blog.csdn.net/SpacePioneer/article/details/84100507
一、题目
Description
输入一行字符,分别统计其中英文字母、空格、数字和其它字符的个数。
Input
键盘上的任意字符串,以;结束。
Output
character= ,blank= ,digit= ,other= ;
Sample Input
case 1:printf("very good!");
Sample Output
character=18,blank=2,digit=1,other=6;
二、解析
本题主要考察字符的操作。思路很简单,因为题目中说了字符串以;结尾(以特定符号结尾的字符串都可以考虑用这种方法操作),使用一个while循环,不断进行getchar()操作,判断得到的字符是否为‘;’,如果是则跳出循环,否则对得到的字符进行判断,创建四个变量分别储存四种字符类型,根据得到的字符对相应变量进行+1,最后按格式输出即可。
三、源码
#include <iostream>
using namespace std;
int main()
{
//分别储存各字符的个数
int character = 0, blank = 0, digit = 0, other = 0;
char ch_in;//接受输入的字符
//循环计算直到检测到分号
while ((ch_in = getchar()) != ';')
{
if (ch_in >= 'a'&&ch_in <= 'z' || ch_in >= 'A'&& ch_in <= 'Z')
character++;
else if (ch_in == ' ')
blank++;
else if (ch_in >= '0'&&ch_in <= '9')
digit++;
else
other++;
}
cout << "character=" << character << ",blank=" << blank << ",digit=" << digit << ",other=" << other << ";";
return 0;
}
四、深入研究
这里说一下,要是没有特定的符号作为结尾却要用这种方法的时候,可以使用字符串变量将整个字符串读入(字符串中有空格的话可能不适用),如果使用while+getchar的话需要对文件尾进行判断,在OJ上提供的数据是以EOF(End of File)结尾的,只要对这个进行判断就能将整个字符串按字符读入。