在做字符串、文本操作时,我们时常会需要在wchar_t *和char *之间做转换或搭桥。直 接用API,参数太多不容易记住,常常要查文档,浪费不少时间。为了自己方便,对简单的转 换写了一个简单的转换包装类。下次或者用得着,帖代码做为保存。
顺便提一下:发现有个东西很好用,std::stringstream系列 (#include < sstream >);其实,流式操作用起来都很happy,还有iostream、fstream;还有TCP的数据也是流 式的。
头文件:string.h
#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__
实现文件:string.cpp
#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 );
}
};
|