这是实现,使用了cstring中的方法: strlen,strcpy两个,来免除一次次对char数组的遍历,
只要把对char数组的下标控制到不越界,即可.考虑到如果在游戏系统中对初始化玩家姓名,生平,等等,对字符串的要求,暂时只做到这样应该能正常的工作吧?
欢迎大家补充.
#include "mystring.h"
#include <cstring>
#include <stdio.h>
int mystring:: sum=0;
mystring::mystring():plen(7)
{
p=new char[plen];
strcpy(p,"deault");
sum++;
n=sum;
}
mystring::~mystring()
{
printf("string %d %p "%s" was deleted (destroy)\n",n,p,p);
sum--;
delete [] p;
}
mystring :: mystring(const char* a)
{
plen = strlen(a)+1;
p= new char [ plen ];
strcpy(p,a);
sum++;
n=sum;
}
mystring :: mystring(const mystring&a)
{
delete []p;
plen= a.plen;
p=new char [ plen ];
strcpy(p,a.p);
sum++;
n=sum;
}
void mystring::operator=(const mystring&a)
{
delete []p;
plen= a.plen;
p=new char [ plen ];
strcpy(p,a.p);
}
void mystring::disp()
{
printf("string %d %p %s (disp)\n",n,p,p);
}
void mystring:: rename(const char*a)
{
delete [] p;
plen = strlen(a) + 1;
p=new char[plen];
strcpy(p,a);
}
void mystring:: rename(int index,char b)
{
if(index<0)
{
printf("string %d min length is 0 "%c" can not replace "%c"\n",
n,b,p[0]);
}
if(index<plen)
{
char t=p[index];
p[index] = b;
printf("string %d %p "%c" was replaced to "%c"\n",n,p,t,b);
}
else if(index==plen)
{
printf("string %d rear is space "%c" can not replace "%c"\n",
n,b,p[plen]);
}
else
{
printf("string %d max length is %d can not use "%c" to replace\n",
n,plen,b);
}
}
|