C++课程设计String类

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include

#include

#include

#include

#define Base 10000

#define M 1000

/*初始长度为Base,以后依次增加M*/

using namespace std;

class String

{

private:

char *str; ///str为指针,len为长度,size为能容纳的最大字符数

int len,size;

public:

///构造函数,能直接确定长度,或者用一个字符串初始化

String (int maxsize=Base);

String (const char *s);

char *c_str() { return str; } ///返回一个指向字符串头部的C语言的指针String insert(int pos,const char c); ///在pos位置插入字符c

String insert(int pos,String s); ///在pos位置插入String s

String insert(int pos,const char *s); ///插入字符串

String Delete(int pos); ///删除pos位置的字符

String Delete(int start,int end); ///删除区间内的字符

String Delete(char c); ///删除所有的c字符

int copy(char *s,int num,int start); ///从start开始复制num个字符到str中

int search(char c); ///返回第一个出现字符c的位置

char operator [] (int pos);

String operator = (String other) ; ///重载= 运算符

String operator = (const char * other) ; ///还是重载,使其支持字符串直接赋值

String operator + (String &other) const; ///重载,返回两个字符串连接

String operator += (String &other) ; ///还是重载,在原String后添加String

bool operator < ( String &other) ; ///重载< ,比较大小

///用重载好了的< ,直接定义其他运算符

bool operator > ( String &other) { return other < *this;}

bool operator >= ( String &other) { return !(*this < other);}

bool operator <= ( String &other) { return !(other < *this);}

bool operator == ( String &other) { return (other <= *this) && (*this <= other);}

bool operator != ( String &other) { return other < *this || *this < other;}

void clear(); ///清空一个字符串

///判断一个String是否为空

bool empty() { if(len==0) return true; return false; }

int length() { return len; } ///返回字符串长度

int max_size() { return size; } ///返回能容纳的字符的最大数量};

///重新定义输入流

istream & operator >> (istream &in, String &other)

{

char s[Base];

in >> s;

other=s;

return in;

}

///重新定义输出流

ostream & operator << (ostream &out,String other)

{

out << other.c_str();

return out;

}

///初始化,若没有参数,则以Base的大小确定

String :: String (int maxsize)

{

str=(char *)malloc(sizeof(char)*maxsize);

memset(str,0,sizeof(str));

len=0;

size=maxsize+M;

}

///用字符串初始化,可以是char *s,也可以使"123"这样的字符串String :: String (const char *s)

{

len=strlen(s);

str=(char *)malloc(sizeof(char)*(len + M));

memset(str,0,sizeof(str));

for(int i=0;i

str[len]=0;

size=len+M;

}

///在pos的位置插入字符c

String String :: insert(int pos,const char c)

{

if(pos<=0 || pos >len) return *this;

相关文档
最新文档