用定长存储方式实现字符串的基本操作(10个基本函数实现)

来源:百度知道 编辑:UC知道 时间:2024/06/23 04:18:43
是在数据结构上做的
使用C语言做的

#include <iostream>
using namespace std;
#include <cstring>

class Str{
char * str;//指向保存字符串的空间
int len;//空间的大小
public:
Str();//无参构造,初始化成零长度字符串
Str(const char* sz);//用指定字符串初始化
Str(const Str&);//拷贝构造函数
~Str();//析构函数,清理空间
int Size() const;//取得字符串长度
Str& operator=(const Str&);//对象间赋值
friend Str operator+(const Str&,const Str&);
Str& operator+=(const Str&);//追加一个字符串
operator int()const;//类型转换函数
friend bool operator==(const Str&,const Str&);//字符串比较
friend ostream& operator<<(ostream& o, const Str&);//输出
friend istream& operator>>(istream& i,Str&);//输入
};
Str::Str()
{
len=100;
str = new char[100];
//if( str==NULL ){...}
str[0]='\0';//zero-length string
}
Str::Str( const char* sz )
{
if( sz==NULL )
sz = "";
len=strlen(sz)+1;
str = new char[len];