现在的位置: 首页 > 综合 > 正文

char*、string和CString字符串之间转换

2013年10月06日 ⁄ 综合 ⁄ 共 868字 ⁄ 字号 评论关闭

    string和CString之间的转换:
    ATL的宏CW2A可以实现两个字节字符串向一个字节字符串转换,如果开发环境使用了宏_UNICODE,则转换方法如下:
CString theCStr;
...
std::string STDCStr(CW2A(theStr.GetString()));
    上面这块代码将实现"在使用者的计算机上进行系统编码"("system encoding on the user's machine"),如果你具体地定义了code page,例如使用UTF-8,则可以使用如下代码:
CString theCStr;
...
std::string STDStr( CW2A(theCStr.GetString(), CP_UTF8) );
    译自http://www.codeproject.com/Tips/175043/Cplusplus-Converting-an-MFC-CString-to-a-std-strin.aspx#alternate1
    ASCII字符串向string字符串转换:
    一般地,把char*字符串转化为Unicode字符串,一般人使用函数MultiByteToWideChar(),但是如果这个单字节字符串只有ASCII符号,使用这个函数就太麻烦了,你可以如下简单编程:
const char* source = "Hello World";
std::wstring result;
std::copy(source, source + strlen(source), back_inserter(result));
    在这页评论中,有人给出了更简单的编码:
std::string source = "Hello World";
std::wstring result(source.begin(), source.end());
    译自http://www.codeproject.com/Tips/174203/ASCII-strings-to-Unicode-in-Cplusplus.aspx#alternate1

抱歉!评论已关闭.