字符更换
前段时间,看到坛里有说指定字串中的字符改字母的,今天写了一个,大家看看符合了要求没有.这是所有的方法,定义了生成对像的总数统计,深复制 和 赋值重载.
另外,把每个对像的总统计数的当前数,复制一份到自己,做成链表的话,应当非常方便.
#ifndef MYSTRING_H
#define MYSTRING_H
class mystring
{
static int sum;
char *p;
int plen,n;
public:
mystring();
~mystring();
mystring(const char*);
mystring(const mystring&);
void operator=(const mystring&);
void disp();
void rename(const char*);
void rename(int index,char b);
protected:
};
#endif 这是实现,使用了cstring中的方法: strlen,strcpy两个,来免除一次次对char数组的遍历,
只要把对char数组的下标控制到不越界,即可.考虑到如果在游戏系统中对初始化玩家姓名,生平,等等,对字符串的要求,暂时只做到这样应该能正常的工作吧?
欢迎大家补充.
#include "mystring.h"
#include <cstring>
#include <stdio.h>
int mystring:: sum=0;
mystring::mystring():plen(7)
{
p=new char;
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;
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);
}
if(index<plen)
{
char t=p;
p = 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);
}
else
{
printf("string %d max length is %d can not use \"%c\" to replace\n",
n,plen,b);
}
}
本帖最后由 howzyao 于 2022-10-15 11:11 编辑
大家对比一下,这两个功效一样,但少了点返回,是返回的好呢,还是直接在调用者的this中改了不返回好呢?
个人偏向到不返回,本质上,调用者总归是改好了嘛,何必返回.
mystring& operator=(const mystring&);
//void operator=(const mystring&);
mystring& mystring:: operator=(const mystring&a)
{
delete []p;
plen= a.plen;
p=new char [ plen ];
strcpy(p,a.p);
return *this;
}
//void mystring::operator=(const mystring&a)
//{
// delete []p;
// plen= a.plen;
// p=new char [ plen ];
// strcpy(p,a.p);
//}
页:
[1]