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

/*
*Copyright (c) 2014, 烟台大学计算机学院
*All rights reserved.
*文件名称:test.cpp
*作者:于凯
*完成日期:2015年 5月 9 日
*版本号:v1.0
*/
#include <iostream>
#include <cstring>
using namespace std;
class String
{
public:
    String();
    String(const char *);
    String operator+(const String &);
    String operator-(const String &);
    void display();
private:
    char *p;
    int len;
};
String::String()
{
    p=NULL;
    len=0;
}
String::String(const char *a)
{
    len=strlen(a);
    p=new char[len+1];
    strcpy(p,a);
}
String String::operator+(const String &s2)
{
    String s;
    s.len=this->len+s2.len;
    s.p=new char[s.len+1];
    strcpy(s.p,this->p);
    strcat(s.p,s2.p);
    return s;
}
String String::operator-(const String &s2)
{
    String s;
    char *c1=new char[this->len+1];
    strcpy(c1,this->p);
    int i=this->len-1;
    while(i>=0&&c1[i]==' ') --i;
    c1[i+1]='\0';
    char *c2=new char[s2.len+1];
    strcpy(c2,s2.p);
    i=0;
    while(i<s2.len&&c2[i]==' ') ++i;
    int j=0;
    while(i<s2.len&&c2[i]!='\0')
    {
        c2[j]=c2[i];
        ++i;
        ++j;
    }
    c2[j]='\0';
    s.len = strlen(c1)+strlen(c2);
    s.p = new char[s.len+1];
    strcpy(s.p,c1);
    strcat(s.p,c2);
    delete c1;
    delete c2;
    return s;
}
void String::display()
{
    cout<<p<<endl;
}
int main()
{
    String s1("dong liang"),s2(" shi zhu zi"),s3;
    s3=s1+s2;
    cout<<"s1+s2=";
    s3.display();
    s3=s1-s2;
    cout<<"s1-s2=";
    s3.display();
    return 0;
}


运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值