std::wstring的相关转换集锦

1、std::wstring转为std::string

    #include 
    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 
#include 
#include 
 
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;
}

你可能感兴趣的:(QT,C++,std::wstring,std::string,const,char*,char*)