自制string类(支持宽字符) (二)

2014-11-24 01:34:34 · 作者: · 浏览: 2
rT *) - 1;

}

template

inline const size_t myString::size()const

{

return M_length;

}

template

void myString::resize(size_t n,charT c)

{

charT *tmp = M_begin;

int i;

M_begin=alloc(n+1);

M_end=M_begin+n;

memcpy((char*)M_begin,(char*)tmp,(n

M_length=strlen((char*)M_begin)/sizeof(charT);

for(i=M_length;i

{

M_begin[i]=c;

}

*M_end='\0';

free(tmp);

}

template

void myString::resize(size_t n)

{

charT *tmp=M_begin;

M_begin=alloc(n+1);

M_end=M_begin+n;

memcpy((char*)M_begin,(char*)tmp,(n

M_length=strlen((char*)M_begin)/sizeof(charT);

free(tmp);

}

////////////////////

// element access //

////////////////////

template

charT& myString::operator[](size_t pos)

{

return M_begin[pos];

}

///////////////

// allocator //

///////////////

template

inline typename myString::iterator myString::alloc(size_t n)

{

M_storage_size=n;

return (charT*)calloc(n,sizeof(charT));

}

///////////////////////

// String operations //

///////////////////////

template

inline const charT* myString::c_str()const

{

return M_begin;

}

template

size_t myString::copy(charT *s, size_t n,size_t pos)const

{

size_t i,j;

assert(pos

for(i=0,j=pos;i

{

s[i]=M_begin[j];

}

return i;

}

template

inline size_t myString::find (const myString& str,size_t pos)const

{

char* p=strstr((char*)M_begin,(char*)str.c_str());

return (p-(char*)M_begin)/sizeof(charT)+1;

}

typedef myString String;

typedef myString WString;

#endif

//vs环境下的测试

#include

#include

#include

#include

#include

#include "my_string.hpp"

int _tmain(int argc, _TCHAR* argv[])

{

setlocale(LC_ALL, "chs");

String st="zh";

String str=st;

printf("str=%s\n",str.c_str());//zxh

wchar_t *w=L"中国人";

WString wstr(w);

wprintf(L"%ls\n",wstr.c_str());//中国人

str="zhanhang";

wstr=L"是中国人";

printf("%s",str.c_str());

wprintf(L"%ls\n",wstr.c_str());//zhanhang是中国人

//operator[] method test

printf("%c\n",str[2]);//a

wprintf(L"%ls\n",&wstr[3]);//人

//iterator method test

String::iterator it;

for(it=str.begin();it!=str.end();it++)

{

printf("%c",*it);

} //zhanhang

printf("\n");

WString::iterator wit=wstr.begin();

wit++;

wprintf(L"%ls\n",wit);//中国人

//resize method test

wstr.resize(6,wstr[0]);

wprintf(L"%ls\n",wstr.c_str()); //是中国人是是

str.resize(2);

printf("%s\n",str.c_str());//zh

str.resize(7,'*');

printf("%s\n",str.c_str());//zh*****

//find method test

str="zhan xin hang";

wstr=L"他是中国人";

String key="xin";

WString wkey=L"中国人";

printf("%d\n",str.find(key)); //6

printf("%d\n",wstr.find(wkey)); //3

//copy method test

wchar_t wbuff[20]={0};

char buff[20]={0};

str.copy(buff,2);

wstr.copy(wbuff,5);

printf("%s",buff);

wprintf(L"%ls\n",wbuff);//zh他是中国人

getch();

return 0;

}

结果如下:

\

//g++环境下的测试

#include

#include

#include"my_string.hpp"

int main()

{