c++字符转化,string<->wstring

 1 /// <summary>
 2 ///utf8转unicode
 3 /// </summary>
 4 bool Utf8ToUnicode( std::string& utf8_string, std::wstring& unicode_string)
 5 {
 6     unicode_string = L"";
 7     if (utf8_string.compare("") == 0 )
 8     {
 9         return false;
10     }
11 
12     const char *temp_utf8_string = utf8_string.c_str();
13     int unicode_string_len = ::MultiByteToWideChar(CP_ACP, NULL, temp_utf8_string, strlen(temp_utf8_string), NULL, 0);
14     if (0 == unicode_string_len )
15     {
16         return false;
17     }
18 
19     wchar_t *temp_unicode_string = new wchar_t[unicode_string_len + 1];
20     memset(temp_unicode_string, 0sizeof(wchar_t) * (unicode_string_len + 1));
21     if (0 == ::MultiByteToWideChar(CP_ACP, NULL, temp_utf8_string, strlen(temp_utf8_string), temp_unicode_string, unicode_string_len))
22     {
23         delete[] temp_unicode_string;
24         temp_unicode_string = NULL;
25         return false;
26     }
27 
28     unicode_string = temp_unicode_string;
29     delete[] temp_unicode_string;
30     temp_unicode_string = NULL;
31 
32     return true;
33 
34 }
35 
36 /// <summary>
37 ///unicode转utf-8
38 /// </summary>
39 bool UnicodeToUtf8( std::wstring& unicode_string, std::string& utf8_string)
40 {
41     utf8_string = "";
42     if (_wcsicmp(unicode_string.c_str(), L"") == 0 )
43     {
44         return false;
45     }
46 
47     DWORD utf8_string_len = WideCharToMultiByte(CP_ACP, NULL, unicode_string.c_str(), -1, NULL, 0, NULL, FALSE);// WideCharToMultiByte的运用
48     if (0 == utf8_string_len)
49     {
50         return false;
51     }
52     char *temp_utf8_string = new char[utf8_string_len + 1];
53     memset(temp_utf8_string, 0sizeof(char) * (utf8_string_len + 1));
54     if (0 == WideCharToMultiByte (CP_ACP, NULL, unicode_string.c_str(), -1, temp_utf8_string, utf8_string_len, NULL, FALSE))
55     {
56         delete[] temp_utf8_string;
57         temp_utf8_string = NULL;
58         return false;
59     }
60 
61     utf8_string = (std::string)temp_utf8_string;
62     delete[] temp_utf8_string;
63     temp_utf8_string = NULL;
64 
65     return true;
66 }

猜你喜欢

转载自www.cnblogs.com/joker-wz/p/9339775.html
今日推荐