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


    作者:朱金灿

    来源:http://blog.csdn.net/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


  • 相关阅读:
    python学习笔记(五)
    python学习笔记(七)
    python小游戏——猜数字2.0
    python学习笔记(六)
    python小游戏——猜数字2.0
    python学习笔记(五)
    python中的in运算符
    python学习笔记(七)
    jmeter(4)响应断言 json断言 beanshell断言
    jmeter(2)几种不同的contenttype方式
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6470743.html
Copyright © 2020-2023  润新知