问题描述
Problem A: 字符统计
Time Limit: 1 Sec Memory Limit: 64 MBSubmit: 226 Solved: 43
[ Submit][ Status][ Web Board]
Description
给出一串字符,要求统计出里面的字母、数字、空格以及其他字符的个数。字母:A, B, ..., Z、a, b, ..., z组成数字:0, 1, ..., 9 空格:" "(不包括引号) 剩下的可打印字符全为其他字符。
Input
测试数据有多组。每组数据为一行(长度不超过100000)。数据至文件结束(EOF)为止。
Output
每组输入对应一行输出。包括四个整数a b c d,分别代表字母、数字、空格和其他字符的个数。
Sample Input
A0 ,
Sample Output
1 1 1 1
代码一:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int letters = 0, numbers = 0, spaces = 0, others = 0;
char array[100000];
while (gets(array))
{
int i = 0;
letters = 0, numbers = 0, spaces = 0, others = 0;
while (array[i])
{
if ((array[i]>='A' && array[i]<='Z') || (array[i]>='a' && array[i]<='z'))
{
++letters;
}
else if (array[i]>='0' && array[i]<='9')
{
++numbers;
}
else if (array[i] == ' ')
{
++spaces;
}
else
{
++others;
}
++i;
}
cout << letters << " " << numbers << " " << spaces << " " << others << endl;
}
return 0;
}
代码二:
利用string类里的一些挺实用的函数。
string::size_type 表示无符号整型,但不容易越界;
isalpha函数是如果是字母,返回true,否则返回false;
isdigit函数是如果是数字,返回true,否则返回false;
isgraph函数是如果不是空格,而是其他可打印的字符,返回true,否则返回false,这里用非;
getline可以包含空格,这里不能用cin。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string str;
while (getline(cin, str))
{
int zimu = 0;
int shuzi = 0;
int kong = 0;
int qita = 0;
for (string::size_type ix = 0; ix != str.size(); ++ix)
{
if (isalpha(str[ix]))
++zimu;
else if (isdigit(str[ix]))
++shuzi;
else if (!isgraph(str[ix]))
++kong;
else
++qita;
}
cout << zimu << " " << shuzi << " " << kong << " " << qita << endl;
}
return 0;
}