字符串里面的字的判断

// 判断某个字符串的某个位置是否是双字节字符的前半个字符
// 如: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 += "…";
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值