2 回答
TA贡献1765条经验 获得超5个赞
//测试程序如下
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <cstdlib>
using namespace std;
class Mystring
{
private:
char *a;
int len;
public:
Mystring()
{
len=0;
}
Mystring(char* s)
{
len=strlen(s);
a=new char[len+1];
memcpy(a,s,len+1);
}
void input() //输入任意长度的字符串
{
char *p = new char[len], ch;
int i = 0;
len = 16;
while(cin>>ch)
{
if(i >= len)
{
char *q = new char[len *= 2];
memcpy(q, p, i);
delete []p;
p = q;
}
p[i++] = ch;
}
len = i;
a = p;
}
void join(const Mystring &s) //在字符串尾部连接上s
{
if(s.len < 1)
return;
int t = s.len + len;
char *q = new char[t]();
memcpy(q, a, len);
memcpy(q+len, s.a, s.len);
a = q;
len = t;
}
~Mystring() //析构函数
{
if(len)
{
delete []a;
a = NULL;
len = 0;
}
}
void Mystring::output()
{
//输出字符串
if(len==0)
cout<<"该字符串为空!"<<endl;
else
{
for(int i = 0; i < len; i++)
{
cout<<a[i];
}
}
}
int Mystring::length()
{
return len;
}
};
void main()
{
// 类Mystring的测试程序
Mystring s1;
cout<<"字符串s1为:";
s1.output();
cout<<"字符串s1的长度为:"<<s1.length()<<endl;
cout<<"请输入一个字符串:";
s1.input();
cout<<"字符串s1为:";
s1.output();
cout<<"字符串s1的长度为:"<<s1.length()<<endl;
Mystring s2("hello!");
cout<<"字符串s2为:";
s2.output();
cout<<"字符串s2的长度为:"<<s2.length()<<endl;
s1.join(s2);
cout<<"连接s2后字符串s1为:";
s1.output();
cout<<"字符串s1的长度为:"<<s1.length()<<endl;
s2.join(s1);
cout<<"连接s1后字符串s2为:";
s2.output();
cout<<"字符串s2的长度为:"<<s2.length()<<endl;
}
添加回答
举报