string与wstring互转

string与wstring互转

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 
/// <summary>
///utf8转unicode
/// </summary>
bool Utf8ToUnicode( std::string& utf8_string, std::wstring& unicode_string)
{
    unicode_string = L
"";
    
if (utf8_string.compare("") == 0 )
    {
        
return false;
    }

    
const char *temp_utf8_string = utf8_string.c_str();
    
int unicode_string_len = ::MultiByteToWideChar(CP_ACP, NULL, temp_utf8_string, strlen(temp_utf8_string), NULL0);
    
if (0 == unicode_string_len )
    {
        
return false;
    }

    
wchar_t *temp_unicode_string = new wchar_t[unicode_string_len + 1];
    memset(temp_unicode_string, 
0sizeof(wchar_t) * (unicode_string_len + 1));
    
if (0 == ::MultiByteToWideChar(CP_ACP, NULL, temp_utf8_string, strlen(temp_utf8_string), temp_unicode_string, unicode_string_len))
    {
        
delete[] temp_unicode_string;
        temp_unicode_string = 
NULL;
        
return false;
    }

    unicode_string = temp_unicode_string;
    
delete[] temp_unicode_string;
    temp_unicode_string = 
NULL;

    
return true;

}

/// <summary>
///unicode转utf-8
/// </summary>
bool UnicodeToUtf8( std::wstring& unicode_string, std::string& utf8_string)
{
    utf8_string = 
"";
    
if (_wcsicmp(unicode_string.c_str(), L"") == 0 )
    {
        
return false;
    }

    DWORD utf8_string_len = WideCharToMultiByte(CP_ACP, 
NULL, unicode_string.c_str(), -1NULL0NULL, FALSE);// WideCharToMultiByte的运用
    if (0 == utf8_string_len)
    {
        
return false;
    }
    
char *temp_utf8_string = new char[utf8_string_len + 1];
    memset(temp_utf8_string, 
0sizeof(char) * (utf8_string_len + 1));
    
if (0 == WideCharToMultiByte (CP_ACP, NULL, unicode_string.c_str(), -1, temp_utf8_string, utf8_string_len, NULL, FALSE))
    {
        
delete[] temp_utf8_string;
        temp_utf8_string = 
NULL;
        
return false;
    }

    utf8_string = (std::string)temp_utf8_string;
    
delete[] temp_utf8_string;
    temp_utf8_string = 
NULL;

    
return true;
}
原文地址:https://www.cnblogs.com/MakeView660/p/8274588.html