此代碼是我參考別的博文所修改,具體出處不太清楚了!
//只保留漢字
int ChineseCharNum(const CString& strSrc)
{
int iLen = strSrc.GetLength();
int iRetLen = 0;
CString strRet;
for(int i=0; i<iLen && (i+1)<iLen; i++)
{
UCHAR c1 = (UCHAR)strSrc.GetAt(i);
UCHAR c2 = (UCHAR)strSrc.GetAt(i+1);
if (c1 < 128)
{
continue;
}
//GB2312中非漢字的編碼
if (((c1>=0xa1&&c1<=0xa9)&&(c2>=0xa1&&c2<=0xfe)) || ((c1>=0xa8&&c1<=0xa9)&&(c2>=0x40&&c2<=0xa0)))
{
i++;
continue;
}
i++;
iRetLen++;
strRet.Insert(strRet.GetLength(),c1);
strRet.Insert(strRet.GetLength(),c2);
//或者使用
//strRet+=strSrc.Mid(i,2);
}
//cout <<strRet.GetBuffer(0) << endl;
return iRetLen;
}