汉字统计
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Problem Description
统计给定文本文件中汉字的个数。
Input
输入文件首先包含一个整数n,表示测试实例的个数,然后是n段文本。
Output
对于每一段文本,输出其中的汉字的个数,每个测试实例的输出占一行。
[Hint:]从汉字机内码的特点考虑~
[Hint:]从汉字机内码的特点考虑~
Sample Input
2
WaHaHa! WaHaHa! 今年过节不说话要说只说普通话WaHaHa! WaHaHa!
马上就要期末考试了Are you ready?
Sample Output
14
9
Author
lcy
ps: 这道题主要是认识一下汉字机内码。一个汉字用两个字节表示,每个字节的最高为都是1,那么转换为int,就为负数,因此只要统计一下有多少个字符的int值为负数,然后最后结果除以2就可以了。
#include<iostream> #include<string> #include<cstdlib> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); string str; int n; cin>>n; cin.get(); while(n--) { int cnt = 0; getline(cin, str); for(int i = 0; i < str.length(); i++) { if((int)str[i] < 0)cnt++; } cout << cnt/2 << endl; } return 0; }