wchar_t、char 、string、 wstring 之间的转换
一、代码
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