话不多说,直接上代码:
bool isGBKCode(const string& strIn)
{
unsigned int nBytes = 0;//GBK可用1-2个字节编码,中文两个 ,英文一个
unsigned char chr = strIn.at(0);
bool bAllAscii = true; //如果全部都是ASCII,
for (unsigned int i = 0; strIn[i] != '\0'; ++i){
chr = strIn.at(i);
if ((chr & 0x80) != 0 && nBytes == 0){// 判断是否ASCII编码,如果不是,说明有可能是GBK
bAllAscii = false;
}
if (nBytes == 0) {
if (chr >= 0x80) {
if (chr >= 0x81 && chr <= 0xFE){
nBytes = +2;
}
else{
return false;
}
nBytes--;
}
}
else{
if (chr < 0x40 || chr>0xFE){
return false;
}
nBytes--;
}//else end
}
if (nBytes != 0) { //违返规则
return false;
}
if (bAllAscii){ //如果全部都是ASCII, 也是GBK
return true;
}
return true;
}