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