Skip to content

字符串类型转换整理(char、TCHAR、string、wstring、CString、WCHAR) #115

@holdyounger

Description

@holdyounger

字符串类型转换整理(char、TCHAR、string、wstring、CString、WCHAR)

[TOC]

string <--> CString

string -> CString

std::string str = &quot;string&quot;;
CString csRet;
// csRet.Format(&quot;%s&quot;, str.c_str());
// 如果上句报错就使用
csRet.Format(_T(&quot;%s&quot;), str.c_str());

CString -> string

CString cstr(&quot;string&quot;);

string 

string < -- > wstring

string -> wstring

solution 1:

#include &lt;string&gt;
#include &lt;locale&gt;
#include &lt;codecvt&gt;
 
//convert string to wstring
inline std::wstring to_wide_string(const std::string&amp; input)
{
	std::wstring_convert&lt;std::codecvt_utf8&lt;wchar_t&gt;&gt; converter;
	return converter.from_bytes(input);
}

solution 2:

wstring stringToWstring(std::string str)
{
    wstring result = L&quot;&quot;;
    int nLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);

    if (nLen == 0)
        return result;

    TCHAR* buffer = new TCHAR[nLen + 1];
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, nLen);

    buffer[nLen] = &#39;&#92;0&#39;;
    result.append(buffer);

    delete[] buffer;
    return result;
}

wstring -> string

//convert wstring to string 
inline std::string to_byte_string(const std::wstring&amp; input)
{
	std::wstring_convert&lt;std::codecvt_utf8&lt;wchar_t&gt;&gt; converter;
	return converter.to_bytes(input);
}

DWORD <---> string

string DwordToString(DWORD val)
{
	string cur_str = to_string(long long (val));
	return cur_str;
}
DWORD StringToDword(string val)
{
	DWORD cur_dword;
	sscanf(val.c_str(),&quot;%ul&quot;,&amp;cur_dword);
	return cur_dword;
}

Unicode 转 字符串

stringToUnicode

UnicodeToStringuToS

blog link 字符串类型转换整理(char、TCHAR、string、wstring、CString、WCHAR)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions