Problem Description
统计给定文本文件中汉字的个数。
Input
输入文件首先包含一个整数n,表示测试实例的个数,然后是n段文本。
Output
对于每一段文本,输出其中的汉字的个数,每个测试实例的输出占一行。
[Hint:]从汉字机内码的特点考虑~
Sample Input
2 WaHaHa! WaHaHa! 今年过节不说话要说只说普通话WaHaHa! WaHaHa!
马上就要期末考试了Are you ready?
Sample Output
14 9
Author
lcy
Source
作者真谐~
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int count = 0;
cin.ignore();
getline(cin, str);
for (int j = 0; j < str.length(); j++)
{
if (str[j] < 0)
{
count++;
j++;
}
}
cout << count << endl;
}
}
代码很容易。因为汉字占两个字符,所以在检测到汉字时,应该让循环变量加2。
汉字由两个汉字组成,其中第一个汉字的第一位是1,所以汉字的第一字符的数值量是个负数。
cin.ignore()用于和getline配合,防止getline获得不必要的数据。