zoukankan      html  css  js  c++  java
  • ANSII 与Unicode,Utf8之间的转换

      在项目开发中,我们难免会遇到各种问题,特别是字符直接的转换,这里列举字符直间转换的代码:

      

    using namespace std;
    
    wstring AnsiiToUnicode(const string& str) {
        // 参数的长度
        int strLen = str.length();
        // 预算-缓冲区中宽字节的长度
        int unicodeLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);
        // 给指向缓冲区的指针变量分配内存
        allocator<wchar_t> wc_t;
        wchar_t *pUnicode = wc_t.allocate(sizeof(wchar_t)*(unicodeLen+1),0);
        // 开始向缓冲区转换字节
        MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pUnicode, unicodeLen);
        wstring ret_str = pUnicode;
        delete pUnicode;
        return ret_str;
    }
    string UnicodeToAssii(const wstring& wstr) {
        // 参数的长度
        int wstrLen = wstr.length();
        // 预算-缓冲区中多字节的长度
        int ansiiLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, nullptr, 0,nullptr,nullptr);
        // 给指向缓冲区的指针变量分配内存
        allocator<char> c_t;
        char *pAssii = c_t.allocate(sizeof(char)*(ansiiLen + 1), 0);
        // 开始向缓冲区转换字节
        WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, pAssii, ansiiLen,nullptr,nullptr);
        string ret_str = pAssii;
        delete pAssii;
        return ret_str;
    }
    wstring Utf8ToUnicode(const string& str) {
        // 参数的长度
        int strLen = str.length();
        // 预算-缓冲区中宽字节的长度
        int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);
        // 给指向缓冲区的指针变量分配内存
        allocator<wchar_t> wc_t;
        wchar_t *pUnicode = wc_t.allocate(sizeof(wchar_t)*(unicodeLen + 1), 0);
        // 开始向缓冲区转换字节
        MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, pUnicode, unicodeLen);
        wstring ret_str = pUnicode;
        delete pUnicode;
        return ret_str;
    }
    string UnicodeToUtf8(const wstring& wstr) {
        // 参数的长度
        int wstrLen = wstr.length();
        // 预算-缓冲区中多字节的长度
        int ansiiLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
        // 给指向缓冲区的指针变量分配内存
        allocator<char> c_t;
        char *pAssii = c_t.allocate(sizeof(char)*(ansiiLen + 1), 0);
        // 开始向缓冲区转换字节
        WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr);
        string ret_str = pAssii;
        delete pAssii;
        return ret_str;
    }
    string AnsiiToUtf8(const string& str) {
        return UnicodeToUtf8(AnsiiToUnicode(str));
    }

     源贴地址:http://tieba.baidu.com/p/4381031865

  • 相关阅读:
    条件判断
    字符串和编码
    排序算法 C++实现
    Ubuntu16.04下 pip的安装与使用
    剑指offer(19): 顺时针打印矩阵
    剑指offer(21):栈的压入、弹出序列
    派生类对象地址赋给基类指针后, 指针对基类和派生类的函数调用
    synergy: error while loading shared libraries: libdns_sd.so.1: cannot open shared object file
    OpenCV Error: Assertion failed + error: (-215) 使用ros opencv中的DNN模块报错
    《 MySQL必知必会 》下载 以及 Ubuntu16.04 下配置其使用的软件环境
  • 原文地址:https://www.cnblogs.com/happinessday/p/6277478.html
Copyright © 2011-2022 走看看