VC判断一个UNICODE字符串中字母、数字、汉字、其他字符的个数

来源:互联网 发布:隔音窗 知乎 编辑:程序博客网 时间:2024/04/27 20:59
void GetCharacterNumber(LPCTSTR szTxt,int &nChinese,int &nEnlish,int &nNumber,int &nOther) 
{
int nLen = WideCharToMultiByte(CP_ACP, 0, szTxt, -1, NULL, 0, NULL, FALSE);
char *szTemp = new char[nLen];
if (!szTemp)
{
delete[]szTemp;
return;
}
WideCharToMultiByte(CP_ACP, 0, szTxt, -1, szTemp, nLen, NULL, FALSE);
CStringA strTxt=szTemp;
delete[]szTemp;
    //获得字符串按字节数计算的长度
    int Lenth = strTxt.GetLength();
    int nELenth = 0;    //英文字符数
    int nCLenth = 0;    //中文字符数
    int nNLenth = 0;    //数字字符数
    int nOLenth = 0;    //其他字符数
    int nTotalLenth = 0;//总共字符数
    for(int i=0;i<Lenth;i++)
    {
        char c = strTxt.GetAt(i);
        //是中文字符 中文字符编码 1XXX XXXX 1XXX XXXX
        if(c<0||c>255)
            continue;
        //是英文字符
        else if((c>='A'&&c<='Z')||(c>='a'&&c<='z'))
            nELenth ++;
else if(c>='0'&&c<='9')
nNLenth++;
else 
nOLenth++;
    }
    //计算中文字符数,每个中文字符占两个字节
    nCLenth = (Lenth-nELenth-nNLenth-nOLenth)/2;
nChinese=nCLenth;
nEnlish=nELenth;
nNumber=nNLenth;
nOther=nOLenth;
}
阅读全文
0 0