#2030:汉字统计--统计给定文本文件中汉字的个数

Problem Description

统计给定文本文件中汉字的个数。

Input

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

Output

对于每一段文本,输出其中的汉字的个数,每个测试实例的输出占一行。

[Hint:]从汉字机内码的特点考虑~

Sample Input

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

Sample Output

14
9

问题分析

  1. 汉字的Ascll码是负值,所以可以通过这点来统计汉字数
  2. 汉字在Ascll码中是两个字节,最后的cnt要除2

完整代码

#include<iostream>
#include<string>
using namespace std;
int main() {
    int n;
    string s;
    while (cin >> n) {
        getchar();//清除键入n值的回车
        while (n--) {
            getline(cin, s);
            int cnt = 0;
            for (int i = 0; i < s.length(); ++i) {
                if (s[i] < 0)cnt++;
            }
            cout << cnt / 2 << endl;//除以字节数
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/RioTian/p/12751329.html