简朴字符串转换
副标题#e#
在做字符串、文本操纵时,我们时常会需要在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__
#p#副标题#e#
实现文件: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 );
}
};