<
CHAR和WHAR的关系
1. 实现CHAR和WCHAR的相互装换
2. 了解TCHAR
>
//char C语言标准数据类型,字符型,至于由几个字节组成通常由编译器决定,一般一个字节
//WCHAR 为Unicode字符,即不论中英文,每个有两个字节组成
/*
TCHAR 如果当前编译方式为 ANSI(默认)方式,TCHAR等价于CHAR,
如果为Unicode方式,TCHAR等价于WCHAR。
*/
*/
wstring StringToWString(const std::string &str)
{
LPCSTR pszSrc = str.c_str();
int nLen = ::MultiByteToWideChar(CP_ACP, 0, pszSrc, -1, NULL, 0);
if (nLen == 0)
return std::wstring(L"");
wchar_t* pwszDst = new wchar_t[nLen];
if (!pwszDst)
return std::wstring(L"");
::MultiByteToWideChar(CP_ACP, 0, pszSrc, -1, pwszDst, nLen);
std::wstring wstr(pwszDst);
delete[] pwszDst;
pwszDst = NULL;
return wstr;
}
string WStringToString(const std::wstring &wstr)
{
LPCWSTR pwszSrc = wstr.c_str();
int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
if (nLen == 0)
return std::string("");
char* pszDst = new char[nLen];
if (!pszDst)
return std::string("");
WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
std::string str(pszDst);
delete[] pszDst;
pszDst = NULL;
return str;
}
std::string UnicodeToUtf8(const wchar_t* buf)
{
int len = ::WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
if (len == 0) return "";
std::vector<char> utf8(len);
::WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);
return &utf8[0];
}
std::wstring AnsiToUnicode(const char* buf)
{
int len = ::MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0);
if (len == 0) return L"";
std::vector<wchar_t> unicode(len);
::MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len);
return &unicode[0];
}
关于 字符集 和字符编码 相关知识 :
请转: http://blog.youkuaiyun.com/wabil/article/details/50807240
再转: http://www.cnblogs.com/houkai/archive/2013/06/04/3116955.html
【 字符集 】:
当我们打开vs新建工程之后,打开工程属性,可以看到该工程的 字符集。
字符集有两种:多字节字符集、Unicode字符集。
【 字符编码方式 】:
常用Unicode的编码方式有: UTF-8、UTF-16
一个头文件,里面集合了一些常用的字符转换方法,可以结合着进行转换
#ifndef _STRTRANFORM_HH
#define _STRTRANFORM_HH
#include <windows.h>
#include<string>
#include<vector>
using namespace std;
wstring AnsiToUnicode(const char* buf)
{
int len = ::MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0);
if (len == 0) return L"";
std::vector<wchar_t> unicode(len);
::MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len);
return &unicode[0];
}
string UnicodeToAnsi(const wchar_t* buf)
{
int len = ::WideCharToMultiByte(CP_ACP, 0, buf, -1, NULL, 0, NULL, NULL);
if (len == 0) return "";
std::vector<char> utf8(len);
::WideCharToMultiByte(CP_ACP, 0, buf, -1, &utf8[0], len, NULL, NULL);
return &utf8[0];
}
wstring Utf8ToUnicode(const char* buf)
{
int len = ::MultiByteToWideChar(CP_UTF8, 0, buf, -1, NULL, 0);
if (len == 0) return L"";
std::vector<wchar_t> unicode(len);
::MultiByteToWideChar(CP_UTF8, 0, buf, -1, &unicode[0], len);
return &unicode[0];
}
string UnicodeToUtf8(const wchar_t* buf)
{
int len = ::WideCharToMultiByte(CP_UTF8, 0, buf, -1, NULL, 0, NULL, NULL);
if (len == 0) return "";
std::vector<char> utf8(len);
::WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, NULL, NULL);
return &utf8[0];
}
#endif