宽字符和窄字符的转换接口

本文提供了一种实用的方法来实现宽字符和窄字符之间的相互转换。通过两个自定义函数toWideString和toNarrowString,可以将ASCII字符串转换为宽字符字符串(wchar_t),反之亦然。这些函数使用了Windows API中的MultiByteToWideChar和WideCharToMultiByte函数。

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

作者:朱金灿

来源:http://blog.youkuaiyun.com/clever101

 

     宽字符和窄字符的转换需求很经常会遇到,今天从网上找了两个函数,修改了一下,奉献给大家。

#include <string>
#include <assert.h>

std::wstring toWideString( const char* pStr,int len)
{
	assert(pStr) ; 
	assert(len >= 0 || len == -1, _T("Invalid string length: ") << len ) ;

	// figure out how many wide characters we are going to get 
	int nChars = MultiByteToWideChar( CP_ACP , 0 , pStr , len , NULL , 0 ) ; 
	if ( len == -1 )
		-- nChars ; 
	if ( nChars == 0 )
		return L"" ;

	// convert the narrow string to a wide string 
	// nb: slightly naughty to write directly into the string like this
	std::wstring buf;
	buf.resize(nChars); 
	::MultiByteToWideChar(CP_ACP,0,pStr,len,const_cast<wchar_t*>(buf.c_str()),nChars); 

	return buf ;
}

std::wstring toWideString(const std::string& strA)
{
	const char* pStr = strA.c_str();
	int len = strA.length();
    return toWideString(pStr,len);
}

std::string toNarrowString( const wchar_t* pStr,int len)
{    
	// figure out how many narrow characters we are going to get 
	assert(pStr) ; 
	assert(len >= 0 || len == -1 , _T("Invalid string length: ") << len ) ; 

	int nChars = WideCharToMultiByte( CP_ACP , 0 , 
		pStr , len , NULL , 0 , NULL , NULL ) ; 
	if ( len == -1 )
		-- nChars ; 
	if ( nChars == 0 )
		return "" ;

	// convert the wide string to a narrow string
	// nb: slightly naughty to write directly into the string like this
	std::string buf ;
	buf.resize(nChars);
	WideCharToMultiByte(CP_ACP,0,pStr,len,const_cast<char*>(buf.c_str()),nChars,NULL,NULL); 

	return buf ; 
}

std::string toNarrowString(const std::wstring& strW)
{
	const wchar_t* pStr = strW.c_str();
	int len = strW.length();
    return toNarrowString(pStr,len);
}


      有问题或者更好意见的话请联系我。

 

参考文献:

 

1. 如何升级基于STL的应用来支持Unicode


评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

clever101

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值