wchar_t,char,string,wstring之间的相互转换

时间:2021-10-11 05:36:10

在处理中文时有时需要进行wchar_t,char,string,wstring之间的转换。

其中char和string之间、wchar_t和wstring之间的转换较为简单,代码在vs2010下测试通过。

复制代码 代码如下:


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

 

using namespace std;

//Converting&nbsp;a&nbsp;WChar&nbsp;string&nbsp;to&nbsp;a&nbsp;Ansi&nbsp;string
char *w2c(char *pcstr,const wchar_t *pwstr, size_t len)
{
 int nlength=wcslen(pwstr);
 //获取转换后的长度
 int nbytes = WideCharToMultiByte( 0, 0, pwstr, nlength, NULL,0,NULL, NULL );
 if(nbytes>len)   nbytes=len;
 // 通过以上得到的结果,转换unicode 字符为ascii 字符
 WideCharToMultiByte( 0,0, pwstr, nlength,   pcstr, nbytes, NULL,   NULL );
 return pcstr ;
}

int main(){

 setlocale(LC_ALL,"chs");
 char* cc = "this is a char 测试";
 wchar_t* wcc = L"this is a wchar 测试";
 string str("this is a string 测试 ");
 wstring wstr = L"this is a wstring 测试";


 //string to char
 const char* char_test = str.c_str();
 //cout<<"char_test:"<<char_test<<endl;

 //char to string
 string ss = cc;
 //cout<<"ss is :"<<ss<<endl;

 //wstring to wchar
 const wchar_t* wchar_test = wstr.c_str();
 //wcout<<wchar_test<<endl;

 //wchar to wstring
 wstring wss = wcc;
 wcout<<wcc<<endl;

 //char to wchar_t
 wchar_t *wc = new wchar_t[str.size()+1];
 //swprintf(wc,L"%S",cc);
 //wcout<<cc<<endl;
 delete []wc;

 // wchar_t to char
 char *pcstr = (char *)malloc(sizeof(char)*(2 * wcslen(wcc)+1));
 memset(pcstr , 0 , 2 * wcslen(wcc)+1 );
 w2c(pcstr,wcc,2 * wcslen(wcc)+1) ;
 free(pcstr);

 system("pause");
 return 1;
}