std::string 與 std::wstring 互轉

前言:

最近接觸了一些 win32 方便的編程,由於不熟 可能會寫一寫這方便的基礎東西 相當於
寫日記了 提升一下

在這裏插入圖片描述

他們的聲明

string 是 char
wstring 是wchar_t

什麼是wchar_t ?

在這裏插入圖片描述

string 轉 wstring

inline
std::wstring StringToWString(const std::string& str)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
	wchar_t* wide = new wchar_t[len + 1];
	memset(wide, '\0', sizeof(wchar_t) * (len + 1));
	MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wide, len);
	std::wstring w_str(wide);
	delete[] wide;
	return w_str;
}

wstring 轉 string


inline
std::string WString2String(const std::wstring& wstr)
{
	int len = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
	char* buffer = new char[len + 1];
	memset(buffer, '\0', sizeof(char) * (len + 1));
	WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
	std::string result(buffer);
	delete[] buffer;
	return result;
}

繼續看兩個接口 MultiByteToWideChar() 與 WideCharToMultiByte()

在這裏插入圖片描述

因爲程序用的是 unicode 編碼 所以 要用 wstring 用寬字符

在這裏插入圖片描述

std::wstring StringToWString(const std::string& str)

int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);

Codepage 我們是UTF-8
dwflag 否
將被轉換的字符串 : str.c_str() 就是 const char *
指定-1 直到空字符串結束 就是末尾
被接受的緩存區 NULL
cchwide char 爲0 返回 緩衝區所需要的寬字符數

len 就是 返回的 緩衝區所需要的寬字符數

這時 我們new wchar_t 長度就是 上面返回的+1 原因是‘\0’
然後 置空

wchar_t* wide = new wchar_t[len + 1];
memset(wide, '\0', sizeof(wchar_t) * (len + 1));

再次調用這個接口 把 str 的數據 放進 wide中 長度爲len

MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wide, len);
std::wstring w_str(wide);
delete[] wide;

然後把 wchar_t 轉爲 wstring delete 掉 wide 然後返回

wstring 轉 string 也是類似 這裏就不說了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章