// 判断某个字符串的某个位置是否是双字节字符的前半个字符
// 如:pStr="abc我们def"
// nPos=3,5时 return ture;
inline bool IsDBCSLead(const char* pStr, int nPos)
{
//int nLen = strlen(pStr);
//if (nPos >= nLen) nPos = nLen - 1;
const unsigned char* str = (const unsigned char*)pStr;
int i = 0;
while (str[i])
{
if (str[i] > 0x80 && ++i > nPos)
return true;
if (++i > nPos)
return false;
}
return false;
}
// 判断某个字符串的某个位置(或位置后面)是否是双字节字符
// 如:pStr="abc我们def"
// nPos=3,4,5,6时 return ture;
// nPos=3,5时是双字节字符的Lead字节
// nPos=4,6时是双字节字符的Trail字节
inline bool IsDBCS(const char* pStr, int nPos)
{
bool bIsDBCS = false;
//int nLen = strlen(pStr);
//if (nPos >= nLen) nPos = nLen - 1;
const unsigned char* str = (const unsigned char*)pStr;
int i = 0;
while (str[i])
{
bIsDBCS = false;
if (str[i] > 0x80)
{
i++;
bIsDBCS = true;
}
if (++i > nPos)
break;
}
return bIsDBCS;
}
inline void FixLenString(string &strInOut, int nExpectation)
{
// 如果长度没有超过期望值, 说明符合要求, 直接返回
if (strInOut.length() <= nExpectation)
{
return;
}
// 前一个字符是中文的话, 说明当前字符是中文两个字符的第二个
bool bIsChiness = IsDBCSLead(strInOut.c_str(), nExpectation - 3);
if (bIsChiness)
{
// 是中文, 则把中文也去掉
strInOut.erase(nExpectation - 3);
}
else
{
// 不是中文, 则去掉后面的
strInOut.erase(nExpectation - 2);
}
strInOut += "…";
}