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 ;
}

转载于:https://www.cnblogs.com/MakeView660/p/8274588.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值