HDU 2030 汉字统计

来源:互联网 发布:mysql against的用法 编辑:程序博客网 时间:2024/06/10 20:45

问题描述:
统计给定文本文件中汉字的个数。

样例输入:
输入文件首先包含一个整数n,表示测试实例的个数,然后是n段文本。

2
WaHaHa! WaHaHa! 今年过节不说话要说只说普通话WaHaHa! WaHaHa!
马上就要期末考试了Are you ready?

样例输出:
对于每一段文本,输出其中的汉字的个数,每个测试实例的输出占一行。
[Hint:]从汉字机内码的特点考虑~

14
9

思路:汉字在内部以两个字节的形式存储,每个字节的第八位都为1,所以可以对字符的二进制码右移7位,判断是否为1,是1则是汉字,否则不是汉字。

AC代码:

#include <cstdio>#include <cstring>#include <iostream>using namespace std;int isH(char c){    if((c >> 7) == 0)         //右移7位为0表示非汉字    {        return 0;    }    return 1;}int main(){    int n;    cin >> n;    cin.ignore();    char s[500];    for(int i = 0; i < n; i++)    {        gets(s);        int cnt = 0;        for(int j = 0; j < strlen(s); j++)        {            if(isH(s[j]))            {                cnt++;                j++;            }        }        printf("%d\n", cnt);    }    return 0;}
0 0
原创粉丝点击