题目描述:
Problem Description
统计给定文本文件中汉字的个数。
Input
输入文件首先包含一个整数n,表示测试实例的个数,然后是n段文本。
Output
对于每一段文本,输出其中的汉字的个数,每个测试实例的输出占一行。
[Hint:]从汉字机内码的特点考虑~
Sample Input
2
WaHaHa! WaHaHa! 今年过节不说话要说只说普通话WaHaHa! WaHaHa!
马上就要期末考试了Are you ready?
Sample Output
14
9
思路:
在计算机中,每个汉字占两个字节,即两个字符,而字节的最高位(符号位)为1,转化为10进制后表现为负值。
因此,可以统计字符串中10进制为负值的字符个数,除以2后就是字符串中汉字的个数。
实现(C++):
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
cin>>n;
getchar();
while(n--){
string sentence;
getline(cin, sentence);
int count=0;
for(int i=0; i<sentence.size(); i++)
if(sentence[i]<0)
count++;
int result=count/2;
cout<<result<<endl;
}
return 1;
}