MFC中Unicode下汉字转换ULR串

CStringA EncodeStr(CStringA strSrc, int sourceCodepage, int targetCodepage)
{
    int  len = strSrc.GetLength();
    int  unicodeLen = MultiByteToWideChar(sourceCodepage, 0, strSrc.GetBuffer(0), -1, NULL, 0);
    wchar_t  *pUnicode;
    pUnicode = new  wchar_t[unicodeLen + 1];
    memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));
    unicodeLen = MultiByteToWideChar(sourceCodepage, 0, strSrc.GetBuffer(0), -1, (LPWSTR)pUnicode, unicodeLen);
    CString  rt1(pUnicode);

    BYTE  *pTargetData=NULL;
    int  targetLen = WideCharToMultiByte(targetCodepage, 0, (LPWSTR)pUnicode, -1, (char  *)pTargetData, 0, NULL, NULL);

    pTargetData = new  BYTE[targetLen + 1];
    memset(pTargetData, 0, targetLen + 1);
    targetLen = WideCharToMultiByte(targetCodepage, 0, (LPWSTR)pUnicode, -1, (char  *)pTargetData, targetLen, NULL, NULL);

    CStringA  rt;
    rt.Format("%s", pTargetData);
    delete[]pUnicode;
    delete[]pTargetData;
    return  rt;
}

// Chinese characters into URL string
CStringA URLEncode(CStringA strSrc)
{
    BYTE byte;
    CStringA strTarget = "";
    CStringA strTempKey = "";
    strSrc = EncodeStr(strSrc, CP_ACP, CP_UTF8);
    for (int i = 0; i < strSrc.GetLength(); i++)
    {
        byte = strSrc.GetAt(i);
        if (0 <= byte&&byte < 128)
        {
            strTempKey.Format("%c", byte);
        }
        else
        {
            strTempKey.Format("%%%02x", byte);
            strTempKey.MakeUpper();
        }
        strTarget += strTempKey;
    }
    return strTarget;
}

你可能感兴趣的:(MFC)