std::wstring的相關轉換集錦

1、std::wstring轉爲std::string

    #include <Windows.h>
    std::string MyClass::WStringToSString(std::wstring fileName) 
	{
 	int nLen = WideCharToMultiByte(CP_ACP, 0, fileName.c_str(), -1, NULL, 0, NULL, 	 NULL); 
	std::string strTemp = ""; 
	if (nLen == 0)
		return strTemp ; 
	strTemp.resize(nLen - 1, 0); 
	WideCharToMultiByte(CP_ACP, 0, fileName.c_str(), -1, (char*)strTemp.c_str(), nLen, NULL, NULL); 
	return strTemp; 
    } 

2、Qt方法wstring轉成 const char*

	std::wstring wstrTemp;
	QString strTemp = QString::fromStdWString(wstrTemp); 
	QByteArray arrayTemp = strTemp.toLocal8Bit();  
	arrayTemp.constData(); //const char*

3、wstring轉成char*

參考鏈接:https://blog.csdn.net/cll131421/article/details/7963446

#include <xstring>
#include <iostream>
#include <comdef.h>
 
using namespace std;
 
char* ws2s(const wstring& ws)
{
 _bstr_t t = ws.c_str(); 
 char* pchar = (char*)t; 
 string result = pchar;
 char* charTmp = new char;
 strcpy(charTmp,result.c_str());
 pchar = NULL;
 delete pchar;
 return charTmp;
}

4、const char*轉換成wstring類型

參考鏈接:https://blog.csdn.net/cqltbe131421/article/details/52597813

std::wstring CATOW(const char* lpcszString)//返回值類型是wstring類型
{
 int unicodeLen = ::MultiByteToWideChar(CP_ACP, 0, lpcszString, -1, NULL, 0);//獲取字符串長度


 wchar_t* pUnicode = new wchar_t[unicodeLen + 1];//開闢寬字節內存
 memset(pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));//清空


 ::MultiByteToWideChar(CP_ACP, 0, lpcszString, -1, (LPWSTR)pUnicode, unicodeLen);//轉換
 std::wstring wString = (wchar_t*)pUnicode;//強轉後賦值給返回變量
 delete[] pUnicode;
 return wString;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章