• C++ std::wstring 互转 std::string


    1、std::wstring 转 std::string

     1 string WstringToString(const std::wstring wstr)
     2 {
     3 #if 1
     4     std::string result;
     5     int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
     6     if( len <= 0 )
     7         return result;
     8  
     9     char* buffer = new char[len + 1];
    10     if(buffer == NULL )
    11         return result;
    12  
    13     WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
    14     buffer[len] = '';
    15     result.append(buffer);
    16     delete[] buffer;
    17  
    18     return result;
    19 #else
    20     //unsigned len = (unsigned)str.size() * 4;
    21     setlocale(LC_CTYPE, "");
    22     //char *p = new char[len];
    23     //wcstombs(p,str.c_str(),len);
    24     //std::string str1(p);
    25     //delete[] p;
    26     //return str1;
    27 #endif
    28 }

    2、std::string 转 std::wstring

     1 wstring StringToWString(const string str) 
     2 {
     3     //int num = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
     4     //wchar_t *wide = new wchar_t[num];
     5     //MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wide, num);
     6     //std::wstring w_str(wide);
     7     //delete[] wide;
     8     //return w_str;
     9  
    10     wstring result;  
    11     //获取缓冲区大小,并申请空间,缓冲区大小按字符计算  
    12     int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);  
    13     TCHAR* buffer = new TCHAR[len + 1];  
    14     //多字节编码转换成宽字节编码  
    15     MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);  
    16     buffer[len] = '';             //添加字符串结尾  
    17     //删除缓冲区并返回值  
    18     result.append(buffer);  
    19     delete[] buffer;  
    20     return result;
    21  
    22 }
  • 相关阅读:
    内存映射mmap的几个api及其使用
    hiredis的安装
    Linux 下解压大全
    redis内存数据库C客户端hiredis API 中文说明
    C/C++使用MySQL
    搜索引擎的缓存(cache)机制
    快速排序(QuickSort)
    冒泡排序
    spring核心之AOP学习总结一
    Spring学习总结六——SpringMVC一
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/15136596.html
Copyright © 2020-2023  润新知