第8周项目4-String类的构造

问题描述:

构造String类的加、减运算。其中,s1 + s2将两个字符串的连接起来;s1 - s2是将s1的尾部空格和s2的前导空格去除后的连接。
提示:有指针成员,设计时要注意。这个,你懂的。

代码:

#include <iostream>
#include <cstring>
using namespace std;
class String
{
public:
   //需要的成员函数(若需要的话,声明友元函数)
   String(const char *s);
   String();
   ~String();
   String(String &s);
   void display();
   String operator+(String &s1);
   String operator-(String &s1);
private:
    char *p;   //指向存储的字符串
    int len;   //记录字符串的长度
};
String::String()
{
    p=NULL;
    len=0;
}
String::String(const char *s)
{
    len=strlen(s);
    p=new char[len+1];

    strcpy(p,s);
}
String::String(String &s)
{
    len=s.len;
    if(p!=NULL) delete []p;;
    p=new char[len+1];
    strcpy(p,s.p);
}
String::~String()
{
    if(!p) delete []p;
}
void String::display()
{
    cout<<p<<endl;
    cout<<len<<endl;
}
String String::operator+(String &s1)
{
    String s;
    s.len=len+s1.len;
    s.p=new char[s.len+1];
    strcpy(s.p,p);
    strcat(s.p,s1.p);
    return s;
}
String String::operator-(String &s1)
{
    char c1[len+1];
    strcpy(c1,p);
    int i=len;
    for(;c1[i]==' ';i--);
    c1[i-1]='\0';
    char c2[s1.len+1];
    strcpy(c2,s1.p);
    int j=0;
    for(i=0;c2[i]==' ';++i);
    while(c2[i]!='\0')
    {
        c2[j]=c2[i];
        ++j;++i;
    }
    c2[j]='\0';
    strcat(c1,c2);
    String s(c1);
    return s;

}
int main()
{
    String s1("study "),s2(" hard"),s3;
    s1.display();
    s2.display();
    s3=s1+s2;
    s3.display();
    s3=s1-s2;
    s3.display();
    return 0;
}


运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值