}
template
inline const size_t myString
{
return M_length;
}
template
void myString
{
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 { 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 { return M_begin[pos]; } /////////////// // allocator // /////////////// template inline typename myString { M_storage_size=n; return (charT*)calloc(n,sizeof(charT)); } /////////////////////// // String operations // /////////////////////// template inline const charT* myString { return M_begin; } template size_t myString { size_t i,j; assert(pos for(i=0,j=pos;i { s[i]=M_begin[j]; } return i; } template inline size_t myString { char* p=strstr((char*)M_begin,(char*)str.c_str()); return (p-(char*)M_begin)/sizeof(charT)+1; } typedef myString typedef myString #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() {