unicode下类型转换
程序员文章站
2022-05-25 08:07:38
...
//unicode
//CString转int
CString m_cstr;
int m_int;
string m_str;
m_cstr = L"100";
m_int = _ttoi(m_cstr);//_ttoi
m_int = 100;
m_cstr.Format(L"%d", m_int);//Format
//CString转string
//方法一
string m_str2(CW2A(m_cstr.GetString())); //采用的方法
//方法二
CT2CA m_ct2ca(m_cstr);
string m_str3(m_ct2ca);
//方法三
wstring m_wstr(m_cstr);
m_str.assign(m_wstr.begin(), m_wstr.end());
//方法四
m_str = CT2A(m_cstr.GetBuffer());//转化为非unicode.
//string转CString
/*c_str()和data()区别是:前者返回带'/0'的字符串,后者则返回不带'/0'的字符串*/
CString m_cstr2(m_str.c_str());
CString m_cstr3(m_str.data());
m_cstr = m_str.c_str();
m_cstr = m_str.data();
m_cstr.Format(L"%s", m_str.c_str());//string->CString
m_cstr.Format(L"%s", m_str.data());//string->CString
//Unicode下CString转换为char*类型
char * m_chr;
m_cstr = _T("hello");
USES_CONVERSION;
m_chr = T2A(m_cstr);//T2A
m_chr = W2A(m_cstr);//W2A
int n = m_cstr.GetLength(); //按字符计算,m_cstr的长度
int len = WideCharToMultiByte(CP_ACP, 0, m_cstr, n, NULL, 0, NULL, NULL);//按Byte计算m_cstr长度
char *chr = new char[len + 1];//按字节为单位
WideCharToMultiByte(CP_ACP, 0, m_cstr, n, chr, len, NULL, NULL);//宽字节转换为多字节编码
chr[len] = '\0'; //不要忽略末尾结束标志
delete[] chr;
//Unicode下char*转换为CString类型
m_chr = "hello";
m_cstr = A2T(m_chr);
m_cstr = A2W(m_chr);
int charLen = strlen(m_chr); //计算pChar所指向的字符串大小,以字节为单位,一个汉字占两个字节
int len = MultiByteToWideChar(CP_ACP, 0, m_chr, charLen, NULL, 0); //计算多字节字符的大小,按字符计算
wchar_t *pWChar = new wchar_t[len + 1]; //为宽字节字符数申请空间,
MultiByteToWideChar(CP_ACP, 0, m_chr, charLen, pWChar, len); //多字节编码转换成宽字节编码
pWChar[len] = '\0';
m_cstr.Append(pWChar);
delete[] pWChar;