字符串在各种编码下的转换

char*   ——》   CStirng

void CharToCString(CString& str, char *chr)

{

    CString pWideChar=_T("");

    //  计算char *数组大小,以字节为单位,一个汉字占两个字节

    int charLen = strlen(chr);    

    //计算多字节字符的大小,按字符计算。

    int len = MultiByteToWideChar(CP_ACP,0,chr,charLen,NULL,0);    

    //为宽字节字符数组申请空间,数组大小为按字节计算的多字节字符大小

    TCHAR *buf = new TCHAR[len + 1];    

    //多字节编码转换成宽字节编码

    MultiByteToWideChar(CP_ACP,0,chr,charLen,buf,len);    

    buf[len] = '\0'; //添加字符串结尾,注意不是len+1    

    //将TCHAR数组转换为CString

    pWideChar.Format(L"%s",buf);

    //删除缓冲区

    delete []buf;

    str=pWideChar;

}

 

CString  ——》  char*

void CStringToChar(CString str, char**chr)

{

    *chr = (char*)malloc(wcslen(str) * 2);

    ::WideCharToMultiByte(CP_ACP,0,str,-1,*chr,wcslen(str) * 2,NULL,NULL);

}

 

Utf-8    ——》  Unicode

void U8ToUnicode(char *Utf8, CString &str)

{

    DWORD dwUnicodeLen;

    TCHAR* pwText;

    dwUnicodeLen = MultiByteToWideChar(CP_UTF8, 0, Utf8, -1, NULL,0);

    pwText = new TCHAR[dwUnicodeLen+1];

    memset(pwText, 0, dwUnicodeLen+1);

    MultiByteToWideChar(CP_UTF8, 0, Utf8, -1, pwText, dwUnicodeLen);

    str.Format( _T("%s"), pwText );

    delete []pwText;

}

 

Unicode  ——》 Utf-8

char* UnicodeToU8(const CString &src)

{

    int len;  

    len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)src, -1, NULL, 0, NULL, NULL);  

    char *szUtf8 = new char[len + 1];

    memset(szUtf8, 0, len + 1);

    WideCharToMultiByte (CP_UTF8, 0, (LPCWSTR)src, -1, szUtf8, len, NULL,NULL);

    return szUtf8;

}

 

你可能感兴趣的:(字符串)