wstring 与 string 的转换
wchar*、wstring 和 char*、std::string 的相互转换
字符串是基本内容,必须要掌握。
string实质上是char字符的字符串。
1 | typedef basic_string< char , char_traits< char >, allocator< char > > |
wstring实质上是wchar_t字符的字符串,即即所谓的宽字符。
1 | typedef basic_string< wchar_t , char_traits< wchar_t >, allocator< wchar_t > > |
同类型字符相互转换
string字符串和char字符数组可以直接相互转换。
5 | const char * pch = str1.c_str(); |
如果想转换到非常量形式char*,可以用strcpy()拷贝到新串,或用const_cast<>运算去掉常量性。
同理,wstring 和 wchar_t数组的转换图上面相同,只不过拷贝串要用wstrcpy()函数。
不同类型字符相互转换
char到wchar_t的转换有好几种,标准C++用流函数os.widen()和os.narrow()可以转换单个字符。
下面用Windows API实现unicode(一般情况下wchar_t使用的编码)和ansi(char使用的编码)的相互转换:
5 | std::string wchar2string( const wchar_t * pwchar ) |
7 | int nLen = WideCharToMultiByte(CP_ACP, 0, pwchar, -1, NULL, 0, NULL, NULL); |
8 | if (nLen<= 0) return std::string( "" ); |
9 | char * pszDst = new char [nLen]; |
10 | if (NULL == pszDst) return std::string( "" ); |
11 | WideCharToMultiByte(CP_ACP, 0, pwchar, -1, pszDst, nLen, NULL, NULL); |
13 | std::string strTemp(pszDst); |
19 | std::string wstring2string( const std::wstring & wstr ) |
21 | return wchar2string(wstr.c_str()); |
25 | std::wstring char2wstring( const char * pchar , int nLen) |
27 | int nSize = MultiByteToWideChar(CP_ACP, 0, ( LPCSTR )pchar, nLen, 0, 0); |
28 | if (nSize <= 0) return NULL; |
29 | WCHAR *pwszDst = new WCHAR [nSize+1]; |
30 | if ( NULL == pwszDst) return NULL; |
31 | MultiByteToWideChar(CP_ACP, 0,( LPCSTR )pchar, nLen, pwszDst, nSize); |
33 | if ( pwszDst[0] == 0xFEFF) |
34 | for ( int i = 0; i < nSize; i ++) |
35 | pwszDst[i] = pwszDst[i+1]; |
36 | std::wstring wcharString(pwszDst); |
42 | std::wstring string2wstring( const std::string & str ) |
44 | return char2wstring(str.c_str(), str.size()); |
48 | wchar_t * char2wchar( const char * pchar , int nLen) |
50 | int nSize = MultiByteToWideChar(CP_ACP, 0, ( LPCSTR )pchar, nLen, 0, 0); |
51 | if (nSize <= 0) return NULL; |
52 | WCHAR *pwszDst = new WCHAR [nSize+1]; |
53 | if ( NULL == pwszDst) return NULL; |
54 | MultiByteToWideChar(CP_ACP, 0,( LPCSTR )pchar, nLen, pwszDst, nSize); |
59 | char * StringManager::wchar2char( const wchar_t * pwchar ) |
61 | int nLen = WideCharToMultiByte(CP_ACP, 0, pwchar, -1, NULL, 0, NULL, NULL); |
62 | if (nLen<= 0) return 0; |
63 | char * pszDst = new char [nLen]; |
64 | if (NULL == pszDst) return 0; |
65 | WideCharToMultiByte(CP_ACP, 0, pwchar, -1, pszDst, nLen, NULL, NULL); |
以上的代码中有重复,应该进一步修改。