字符统计

问题描述

Problem A: 字符统计

Time Limit: 1 Sec   Memory Limit: 64 MB
Submit: 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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值