宽字符串和标准字符串的转换

本文介绍如何在C++中高效地进行字符串与宽字符字符串之间的转换,并提供了实用的代码示例。从基础概念到具体实现,涵盖多种场景,旨在帮助开发者提升字符串操作能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

string WstringToString(wstring str)
{
const wchar_t *pwc=str.c_str();
int nLen=WideCharToMultiByte(CP_ACP,0,(LPCWSTR)pwc,-1,NULL,0,NULL,NULL);
if(nLen<=0) return string("");
char *presult=new char[nLen];
if (NULL==presult) return string("");
WideCharToMultiByte(CP_ACP,0,(LPCWSTR)pwc,-1,presult,nLen,NULL,NULL);
presult[nLen-1]=0;
string result(presult);
delete[] presult;
return result;
}
wstring StringToWstring(string str)
{
const char *pstr=str.c_str();
int nLen=str.size();
int nSize=MultiByteToWideChar(CP_ACP,0,(LPCSTR)pstr,nLen,0,0);
if (nSize<=0) return NULL;
WCHAR *pDst=new WCHAR[nSize+1];
if (pDst==NULL)return NULL;
MultiByteToWideChar(CP_ACP,0,(LPCSTR)pstr,nLen,pDst,nSize);
pDst[nSize]=0;
if (pDst[0]==0xFEFF)
{
for (int i=0;i<nSize;i++)
{
pDst[i]=pDst[i+1];
}
}
wstring wcstr(pDst);
delete []pDst;
return wcstr;
}


//下面是一位朋友写的,被我剽窃了
class auto_setlocate
{
public:
auto_setlocate()
{
setlocale(LC_ALL, "");
}
};

std::string wstring2string(const wchar_t* wsz)
{
static auto_setlocate as;
std::string ret(wcslen(wsz)*2, '/0');
std::wcstombs(const_cast<char*>(ret.c_str()), wsz, ret.length());
return ret;
}

std::string wstring2string(const std::wstring& wstr)
{
static auto_setlocate as;
std::string ret(wstr.length()*2, '/0');
std::wcstombs(const_cast<char*>(ret.c_str()), wstr.c_str(), wstr.length());
return ret;
}

std::wstring string2wstring(const char* sz)
{
static auto_setlocate as;
std::wstring ret(strlen(sz), '/0');
std::mbstowcs(const_cast<wchar_t*>(ret.c_str()), sz, ret.length());
return ret;
}

std::wstring string2wstring(const std::string& str)
{
static auto_setlocate as;
std::wstring ret(str.length(), '/0');
std::mbstowcs(const_cast<wchar_t*>(ret.c_str()), str.c_str(), str.length());
return ret;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值