读书人

CString转换UTF-8,该如何处理

发布时间: 2012-06-01 16:46:36 作者: rapoo

CString转换UTF-8

C/C++ code
char *pElementText;    int iTextLen;    // wide char to multi char    iTextLen = WideCharToMultiByte( CP_UTF8,0,str,-1,NULL,0,NULL,NULL );    pElementText = new char[iTextLen + 1];    memset( ( void* )pElementText, 0, sizeof( char ) * ( iTextLen + 1 ) );    ::WideCharToMultiByte( CP_UTF8,0,str,-1,pElementText,iTextLen,NULL,NULL );    CString strText;    strText = pElementText;    delete[] pElementText;    return strText;


我是想把 CString字符串转换成 %ED%95%98%EB%A3%A8%ED%95%9C%EB%81%BC 这种格式的字符串,应该是UTF8的吧。可是转完了是乱码,怎么办啊。 请大侠们给出详细的代码,转完不乱码,拜服

[解决办法]
首先将你的 cstring 转到 utf8

给你抄一段代码
C/C++ code
char* __stdcall UnicodeToUtf8( const WCHAR* wstr ){    const WCHAR* w;    // Convert unicode to utf8    int len = 0;    for ( w = wstr; *w; w++ ) {        if ( *w < 0×0080 ) len++;        else if ( *w < 0×0800 ) len += 2;        else len += 3;    }    unsigned char* szOut = ( unsigned char* )malloc( len+1 );    if ( szOut == NULL )        return NULL;    int i = 0;    for ( w = wstr; *w; w++ ) {        if ( *w < 0×0080 )            szOut[i++] = ( unsigned char ) *w;        else if ( *w < 0×0800 ) {            szOut[i++] = 0xc0 | (( *w ) >> 6 );            szOut[i++] = 0×80 | (( *w ) & 0x3f );        }        else {            szOut[i++] = 0xe0 | (( *w ) >> 12 );            szOut[i++] = 0×80 | (( ( *w ) >> 6 ) & 0x3f );            szOut[i++] = 0×80 | (( *w ) & 0x3f );        }    }    szOut[ i ] = ‘\0‘;    return ( char* )szOut;} 

读书人网 >VC/MFC

热点推荐