C++各种字符串转码实现集合

string -> wstring

std::wstring StringToWstring(const std::string& str)
{
	std::wstring result;

	//获取缓冲区大小,并申请空间,缓冲区大小按字符计算  
	int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), nullptr, 0);
	TCHAR* buffer = new TCHAR[2*(len + 1)];

	//多字节编码转换成宽字节编码  
	MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);

	//添加字符串结尾  
	buffer[len] = '\0';

	//删除缓冲区并返回值  
	result.append(buffer);
	delete[] buffer;
	return result;
}

wstring -> string

bool UnicodeToUtf8(std::wstring& unicodeString, std::string& utf8String)
{
    utf8String = "";
    if (_wcsicmp(unicodeString.c_str(), L"") == 0)
    {
        return false;
    }

    DWORD utf8StringLen = WideCharToMultiByte(CP_ACP, NULL, unicodeString.c_str(), -1, NULL, 0, NULL, FALSE);// WideCharToMultiByte的运用
    if (0 == utf8StringLen)
    {
        return false;
    }
    char* tempUtf8String = new char[utf8StringLen + 1];
    memset(tempUtf8String, 0, sizeof(char) * (utf8StringLen + 1));
    if (0 == WideCharToMultiByte(CP_ACP, NULL, unicodeString.c_str(), -1, tempUtf8String, utf8StringLen, NULL, FALSE))
    {
        delete[] tempUtf8String;
        tempUtf8String = NULL;
        return false;
    }

    utf8String = (std::string)tempUtf8String;
    delete[] tempUtf8String;
    tempUtf8String = NULL;

    return true;
}

更改string编码为gbk格式

std::string UTF8ToGB(const char* str)
{
    std::string result;
    WCHAR* strSrc;
    LPSTR szRes;

    //获得临时变量的大小
    int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
    strSrc = new WCHAR[i + 1];
    MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);

    //获得临时变量的大小
    i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
    szRes = new CHAR[i + 1];
    WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);

    result = szRes;
    delete[]strSrc;
    delete[]szRes;

    return result;
}

wchar_t* -> string

void Wchar_tToString(std::string& szDst,  wchar_t* wchar)
{
    wchar_t* wText = wchar;

    // WideCharToMultiByte的运用
    DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, NULL, 0, NULL, FALSE);

    // psText为char*的临时数组,作为赋值给std::string的中间变量
    char* psText; 
    psText = new char[dwNum];

    // WideCharToMultiByte的再次运用
    WideCharToMultiByte(CP_OEMCP, NULL, wText, -1, psText, dwNum, NULL, FALSE);
    szDst = psText;// std::string赋值
    delete[]psText;// psText的清除
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值