wchar_t、char 、string、 wstring 类型相互转换

这篇博客详细介绍了在C++环境下,如何进行wchar_t、char、string以及wstring之间的相互转换,包括string转char、char转string、wstring转wchar、wchar转wstring、char转wchar_t、wchar_t转char、wstring转string以及string转wstring等操作。在Linux系统中,由于缺乏Windows中的WideCharToMultiByte和MultiByteToWideChar函数,作者推荐使用mbstowcs和wcstombs作为替代方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、代码

1.1 string 转 char

#include <iostream>
#include <string>
#include <tchar.h>
#include <Windows.h>

string str("这是一个字符串 ");
const char* cc_str = str.c_str(); 

1.2 char 转 string

#include <iostream>
#include <string>
#include <tchar.h>
#include <Windows.h>

char* c = "这是一个字符类型";
string ss = c;

1.3 wstring 转 wchar

#include <iostream>
#include <string>
#include <tchar.h>
#include <Windows.h>

wstring wstr = L"这是一个宽字符串";
const wchar_t* wchar_test = wstr.c_str(); 

1.4 wchar 转 wstring

#include <iostream>
#include <string>
#include <tchar.h>
#include <Windows.h>

wchar_t* wc = L"这是一个宽字符";
wstring wss = wc;

1.5 char 转 wchar_t

#include <iostream>
#include <string>
#include <tchar.h>
#include <Windows.h>

string str("这是一个字符串 ");
wchar_t *wc = new wchar_t[str.size()+1];

1.6 wchar_t 转 char

#include <iostream>
#include <string>
#include <tchar.h>
#include <Windows.h>

wchar_t* wc = L"这是一个宽字符";
char *c_str = (char *)malloc(sizeof(char)*(2 * wcslen(wc)+1));
memset(c_str , 0 , 2 * wcslen(wc)+1 );
int w_len=wcslen(wc);
int bytes = WideCharToMultiByte( 0, 0, wc, w_len, NULL,0,NULL, NULL );
if(bytes>2 * wcslen(wc)+1)   bytes=2 * wcslen(wc)+1;
WideCharToMultiByte( 0, 0, wc, w_len,  c_str , bytes, NULL,   NULL );
free(c_str);

1.7 wstring转string

//linux ubuntu系统下

#include <string><br>
#include <stdlib.h><br>
#include <locale.h>
std::string W2S(const std::wstring& wstr)
{
    std::string curLocale = setlocale(LC_ALL, NULL);
    setlocale(LC_ALL, "chs");
    const wchar_t* _Source = wstr.c_str();   //wstring-->wchar_t
    size_t _Dsize = 2 * wstr.size() + 1;
    char *_Dest = new char[_Dsize];
    memset(_Dest,0,_Dsize);
    wcstombs(_Dest,_Source,_Dsize);
    std::string result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, curLocale.c_str());
    return result;
}

1.8 string转wstring

std::wstring S2W(const std::string& astr)
{
    setlocale(LC_ALL, "chs");
    const char* _Source = astr.c_str();
    size_t _Dsize = astr.size() + 1;
    wchar_t *_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 0, _Dsize);
    mbstowcs(_Dest,_Source,_Dsize);
    std::wstring result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, "C");
    return result;
}

二、参考链接

linux没有WideCharToMultiByte,MultiByteToWideChar,换用mbstowcs,wcstombs

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自动驾驶探索站

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值