• Unicode编码下字符串转换


    VCMFC当中CString、string、char、char*、char数组、int等类型之间的转换令人晕头转向,特地搜集多篇文章资料,利用代码实例等清晰的理清他们之间的关系和如何转换,其实非常简单。

    1、CString std::string互转
    std::string strstring = "std::string";
    CString strCString = _T("CString");

    //CString->std::string
    strstring = CStringA(strCString);


    //std::string->CString
    strCString = strstring.c_str();

    2、int和CString
    //CString->int
    CString strInt = _T("123");
    int n = 0;
    n = _ttoi(strInt);
    n = 9;
    //int->CString
    strInt.Format(_T("%d"), n);

    3、double和CString
    CString strdouble = _T("123.00");
    double dVal = 0;
    //CString->double
    dVal = _tstof(strdouble);
    dVal = 999.0;
    //double->CString
    strdouble.Format(_T("%f"), dVal);

    //4、char*和CString
    char* chchar = "chahdaslhdf";
    CString strCh = _T("char");
    //char*->CString
    strCh = chchar;
    //或者
    //预转换,得到所需空间的大小
    int wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, chchar, strlen(chchar), NULL, 0);
    //分配空间要给''留个空间,MultiByteToWideChar不会给''空间
    wchar_t* wszString = new wchar_t[wcsLen + 1];
    //转换
    ::MultiByteToWideChar(CP_ACP, NULL, chchar, strlen(chchar), wszString, wcsLen);
    //最后加上''
    wszString[wcsLen] = '';
    //附加到CString对象上
    CString content;
    content.Append(wszString);

    //CString->char*
    int n = strCh.GetLength(); //按字符计算,strCh的长度

    int len = WideCharToMultiByte(CP_ACP, 0, strCh, n, NULL, 0, NULL, NULL);//按Byte计算str长度
    char *pChStr = new char[len+1];//按字节为单位
    memset(pChStr,0,len+1);
    WideCharToMultiByte(CP_ACP, 0, strCh, n, pChStr, len, NULL, NULL);//宽字节转换为多字节编码
    pChStr[len] = '';
    memcpy(chDis, pChStr, len + 1);
    delete []pChStr;

    CString转char*

    char* ch = new char;
    CString str1 = _T("12121");
    strcpy(ch, CStringA(str1).GetString());

    5、将wchar_t*转化为char*

    char* UnicodeToAnsi(const wchar_t* szStr)
    {
        int nLen = WideCharToMultiByte( CP_ACP, 0, szStr, -1, NULL, 0, NULL, NULL );
        if (nLen == 0)
        return NULL;

        char* pResult = new char[nLen+1];
        WideCharToMultiByte( CP_ACP, 0, szStr, -1, pResult, nLen, NULL, NULL );
        return pResult;
    }

    6、将char*转化为wchar_t*

    wchar_t* AnsiToUnicode(const char* szStr)
    {
        int nLen = MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, NULL, 0 );
        if (nLen == 0)
        return NULL;

        wchar_t* pResult = new wchar_t[nLen+1];
        MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, szStr, -1, pResult, nLen );
        return pResult;
    }

    7、头文件#include <sstream>
    //int->string
    int n1 = 0;
    std::stringstream ssCov;
    std::string str;
    ssCov<<n1;
    ssCov>>str;


    //string->int
    std::string strNum = "123";
    int n2 = atoi(strNum.c_str());

  • 相关阅读:
    windows10输入法评价
    找水王
    团队项目第九天
    团队项目第八天
    团队项目第七天
    团队项目第六天
    团队项目第四天
    团队项目第五天
    团队项目第三天
    团队项目第二天
  • 原文地址:https://www.cnblogs.com/lpxblog/p/4597420.html
Copyright © 2020-2023  润新知