//问题描述:统计字符串中的汉字个数。
//解题思路是:从汉字机内码的特点考虑:一个汉字是有两个ASCII字符构成,且这两个字符的ASCII码值小于0。
#include <iostream>
#include <string>
using namespace std;
int GetChineseCharacterCounts(string str) //统计字符串str中的汉字个数
{
int len=str.size(); //求出str中的有效字符的个数(不包括终结符)
int counts=0; //汉字的个数
for(int i=0; i<len;)
{
if(str[i] <0)
{
++counts;
i+=2;
}
else
{
++i;
}
}
return counts;
}
int GetChineseCharacterCounts(const char* pStr) //求出字符串pStr中的汉字个数
{
int counts=0;
while(*pStr !='\0')
{
if(*pStr <0)
{
++counts;
pStr+=2;
}
else
{
++pStr;
}
}
return counts;
}
int main()
{
//C++风格
string str;
cout<<"输入一个字符串:";
cin>>str;
cout<<"该字符串是:"<<str<<endl;
int counts=GetChineseCharacterCounts(str); //求出str中的汉字个数
cout<<"该字符串的汉字个数是:"<<counts<<endl;
//C风格
char string[100];
cout<<"

该博客介绍了如何统计字符串中汉字的数量。通过分析汉字机内码的特性,我们知道每个汉字由两个ASCII字符组成,且这两个字符的ASCII码值小于0。解题的关键在于识别这种特定的编码模式。
5532

被折叠的 条评论
为什么被折叠?



