分类:
2008-10-13 16:10:35
#pragma once #ifndef __STRING__ #define __STRING__ /** * 以下代码由张家旺编写完成于2007-12-5,借用请保留该声明。 */ namespace useful { class translator { public: static wchar_t *translate( const char *str,size_t sub,wchar_t buf[],size_t num ); static char *translate( const wchar_t *str,size_t sub,char buf[],size_t num ); const wchar_t *translate( const char *str,size_t sub = -1 ); const char *translate( const wchar_t *str,size_t sub = -1 ); translator( void ); ~translator( void ); static translator &instance( void ); private: void buffer( size_t len ) { if( len > m_len ) { delete[] m_buf; m_buf = new char[len]; m_len = len; } } char *m_buf; size_t m_len; }; }; #endif //__STRING__
#include < string > #include < windows.h > #include "./string.h" #pragma warning( disable : 4267 ) namespace useful { translator::translator( void ) : m_buf( 0 ),m_len( 0 ) { } translator::~translator( void ) { delete[] m_buf; } translator &translator::instance( void ) { static translator impl = translator(); return impl; } wchar_t *translator::translate( const char *str,size_t sub,wchar_t buf[],size_t num ) { ::MultiByteToWideChar( CP_OEMCP,0,str,sub,buf,num ); return buf; } char *translator::translate( const wchar_t *str,size_t sub,char buf[],size_t num ) { ::WideCharToMultiByte( CP_OEMCP,0,str,sub,buf,num,0,0 ); return buf; } const wchar_t *translator::translate( const char *str,size_t sub ) { if( sub == std::string::npos ) sub = strlen( str ); buffer( (sub+1) * 2 ); wchar_t *buf = reinterpret_cast< wchar_t * >( m_buf ); buf[sub] = L'\0'; return translate( str,sub,buf,sub ); } const char *translator::translate( const wchar_t *str,size_t sub ) { if( sub == std::wstring::npos ) sub = wcslen( str ); buffer( sub + 1 ); m_buf[sub] = '\0'; return translate( str,sub,m_buf,sub ); } };