/*
*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;
}
运行结果: