天天看点

VC++编程中常用的字符串转换函数

VC++编程中经常遇到不同编码编码的字符串之间需要转换的情况,以下简单提供几个不同编码字符串之间的转换函数:

ANSI 字符串和Unicode字符串之间的转换

//Convert wide char string to ANSI string
BOOL WCharToMByte(LPCWSTR lpcwszStr,Std::string &str)
{
    DWORD dwMinSize=0;
    LPSTR lpszStr=NULL;
    dwMinSize= WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE);
    if(0==dwMinSize)
    {
        return FALSE;
    }
    lpszStr=new char[dwMinSize];
    WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,lpszStr,dwMinSize,NULL,FALSE);
    str=lpszStr;
    delete []lpszStr;
    return TRUE;
}

//Convert ANSI string to wide char string
BOOL MByteToWChar(LPWSTR lpcwszStr,std::string str)
{
    size_t size=str.length();
    wchar_t *buffer=new wchar_t[size+1];
    MultiByteToWideChar(CP_ACP,NULL,str.c_str(),size,buffer,size*sizeof(wchar_t));
    buffer[size]=0;
    lpcwszStr=buffer;
    delete buffer;
    return TRUE;
}      

View Code

待续。。。

转载于:https://www.cnblogs.com/chengbing2011/p/4088291.html