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),  NULL 0 );
    
if  ( 0  == unicode_string_len )
    {
        
return   false ;
    }

    
wchar_t  *temp_unicode_string =  new   wchar_t [unicode_string_len +  1 ];
    memset(temp_unicode_string, 
0 sizeof ( 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(), - 1 NULL 0 NULL , FALSE); // WideCharToMultiByte的運用
     if  ( 0  == utf8_string_len)
    {
        
return   false ;
    }
    
char  *temp_utf8_string =  new   char [utf8_string_len +  1 ];
    memset(temp_utf8_string, 
0 sizeof ( 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 ;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM