写一个能处理字符串的类。
#include <iostream> #include <Cstring> using namespace std; class String { public: String( ); //默认构造函数 String(const char *s); String(String &str); //构造函数 ~String(); void display( ); friend String operator + (String &s1,String &s2 ); friend String operator - (String &s1,String &s2 ); private: char *p; int len; //字符型指针,用于指向字符串 }; String::String() { len = 0; p = NULL; } String::String(const char *s) { len = strlen(s); p = new char[len+1]; strcpy(p,s); } String::String(String &str) { len = str.len; if(p!=NULL) delete []p; //当发生在赋值等情形时,原对象可能已经存在,需释放原有空间 p = new char[len+1]; strcpy(p,str.p); } String::~String() { if(!p) delete []p; } void String::display( ) //输出p所指向的字符串 { cout<<p<<endl; } String operator + (String &s1, String &s2 ) { String s; s.len = s1.len+s2.len; s.p = new char[s.len+1]; //原误写char(s.len+1) strcpy(s.p,s1.p); strcat(s.p,s2.p); return s; } String operator - (String &s1, String &s2 ) { String s; //c1为截去尾部空格的字符串 char *c1=new char[s1.len+1]; strcpy(c1,s1.p); int i=s1.len-1; while(i>=0&&c1[i]==' ') --i; c1[i+1]='\0'; //c2为去除前导空格的字符串 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]; //原误写char(s.len+1) strcpy(s.p,c1); strcat(s.p,c2); delete c1; delete c2; return s; } int main( ) { String string1("zs "), string2(" 9528"); string1.display(); string2.display(); String string3; string3 = string1 + string2; string3.display(); string3 = string1 - string2; string3.display(); return 0; }
运行结果:
时间: 2024-10-26 14:51:50