汉字统计
Problem Description
统计给定文本文件中汉字的个数。
Input
输入文件首先包含一个整数n,表示测试实例的个数,然后是n段文本。
Output
对于每一段文本,输出其中的汉字的个数,每个测试实例的输出占一行。
[Hint:]从汉字机内码的特点考虑~
Sample Input
2
WaHaHa! WaHaHa! 今年过节不说话要说只说普通话WaHaHa! WaHaHa!
马上就要期末考试了Are you ready?
Sample Output
14
9
问题链接:http://acm.hdu.edu.cn/showproblem.php?pid=2030
问题分析:
- 汉字机内码在计算机的表达方式的描述是,使用二个字节,每个字节最高位一位为1。
- 汉字的ascii码是小于0的,一个汉字占两个字节,所以最后要除以2。
源代码
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <iterator>
#include <cstring>
#include <cctype>
#include <stack>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
getchar(); //吃回车键
while(n--)
{
char s[500];
gets(s);
int len = strlen(s);
int cnt = 0;
for(int i = 0; i < len; i++)
{
if(s[i] < 0) //汉字的ASCII码小于0
cnt++;
}
printf("%d\n", cnt/2); //一个汉字占两个字节,所以最后要除以2
}
return 0;
}