文字长度判断,汉字,字母,数字,图片都算作一个长度单位

const int MAX_CHAT_LENGTH = 10;
 
std::string utf8_to_gbk(const char *utf8)
{
 int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
 std::shared_ptr<wchar_t> wstr(new wchar_t[len + 1]);
 memset(wstr.get(), 0x00, sizeof(wchar_t) * (len + 1));
 MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr.get(), len);
 len = WideCharToMultiByte(CP_ACP, 0, wstr.get(), -1, NULL, 0, NULL, NULL);
 std::shared_ptr<char> str(new char[len + 1]);
 memset(str.get(), 0x00, sizeof(char) * (len + 1));
 WideCharToMultiByte(CP_ACP, 0, wstr.get(), -1, str.get(), len, NULL, NULL);
 return str.get(); 
}

std::wstring string_to_wstring(const std::string& s)
{
 _bstr_t t = s.c_str();
 wchar_t* pwchar = (wchar_t*)t;
 std::wstring result = pwchar;
 return result;
}

  
int string_len(std::string utf8_str)
{
 if(utf8_str.size() > 0)
 {
  char buf[1024] = {0};
  char dest_buf[2] = {0};
  memset(buf, 0, 1024);
  memset(dest_buf, 0, 2);
  strcpy(buf, utf8_str.c_str());
  std::string convert_str;
  bool convert_flag = true;
  bool begin = false;
  int count = 0;
  for(int i = 0; i < strlen(buf); ++i)
  {
   if(buf[i] == '<' && buf[i+1] == 'i' && buf[i+2] == 'm' && buf[i+3] == 'a' && buf[i+4] == 'g' && buf[i+5] == 'e' && buf[i+6] == 's' && buf[i+7] == '>')
   {
    convert_flag = false;
   }
   if(convert_flag == false && buf[i] == '<' && buf[i+1] == '/' && buf[i+2] == 'i' && buf[i+3] == 'm' && buf[i+4] == 'a' && buf[i+5] == 'g' && buf[i+6] == 'e' && buf[i+7] == 's' && buf[i+8] == '>')
   {
    begin = true;
   }
   if(begin && buf[i] == '>')
   {
    convert_flag = true;
    begin = false;
    ++count;
   }
   if(count > 5)
   {
    return MAX_CHAT_LENGTH + 1;
   }
   if(convert_flag)
   {
    dest_buf[0] = buf[i];
    convert_str = convert_str + dest_buf;
    memset(dest_buf, 0, 2);
   }
  }
  std::string gbk_str = utf8_to_gbk(convert_str.c_str());
  std::wstring ws_str = string_to_wstring(gbk_str.c_str());
  return ws_str.size();
 }
 else
 {
  return MAX_CHAT_LENGTH + 1;
 }
 
}

转载于:https://my.oschina.net/ifraincoat/blog/418084

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值