std::string互转UTF-8,std::wstring互转UTF-8

时间:2021-05-09 20:23:49

std::string 转 UTF-8:

char *  string_To_UTF8 (const std::string & str)
{
    int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
    wchar_t* pwBuf = new wchar_t[nwLen + 1];
    ZeroMemory(pwBuf, nwLen * 2 + 2);

    ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);
    int nLen = ::WideCharToMultiByte( CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
    char* pBuf = new char[nLen + 1];

    ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

    return pBuf;
}

std::wstring 转 UTF-8:

char * wstring_To_UTF8(const std::wstring & str)
{
    int nLen = ::WideCharToMultiByte( CP_UTF8, 0, str.c_str(), -1, NULL, NULL, NULL, NULL);
    char* pBuf = new char[nLen + 1];
    ::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), nLen, pBuf, nLen, NULL, NULL);
    return pBuf;
}

UTF-8 转 std::string:

char* UTF8_To_string(const std::string & str)
{
    int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
    wchar_t * pwBuf = new wchar_t[nwLen + 1];
    memset(pwBuf, 0, nwLen * 2 + 2);

    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);
    int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
    char * pBuf = new char[nLen + 1];
    memset(pBuf, 0, nLen + 1);

    WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

    return pBuf;

}

std::string  stdstr = UTF8_To_string(str);