您的位置:首页 > 理论基础 > 数据结构算法

Sting 串实现

2015-10-28 21:23 337 查看
完全按照primer plus 手打

String.h:

/*=============================================================================
#
#      Author: liangshu - cbam
#
#      QQ : 756029571
#
#      School : 哈尔滨理工大学
#
#      Last modified: 2015-10-28 21:21
#
#     Filename:
#
#     Description:
#        The people who are crazy enough to think they can change the world, are the ones who do !
=============================================================================*/
#
#ifndef STRING_H
#define STRING_H
#include<iostream>
using std::ostream;
using std::istream;
class String
{
public:
String();
String(const char *s);
~String();
int length()const {return len;}
String &operator = (const String &);
String &operator = (const char *);
char &operator[](int i);
const char &operator[](int i)const;

friend bool operator < (const String &st, const String &st2);
friend bool operator > (const String &st, const String &st2);
friend bool operator == (const String &st, const String &st2);
friend ostream & operator<< (ostream &os, const String &st);
friend istream & operator >> (istream &is, String &st);
static int Howmany();

private:
char *str;
int len;
static int num_strings;
static const int CINLIM = 80;
};

#endif // STRING_H
String.cpp:

#include<cstring>
#include"String.h"
using std::cin;
using std::cout;
int String :: num_strings = 0;
int String::Howmany(){
return num_strings;
}

String::String(const char *s){
len = strlen(s);
str = new char[len + 1];
str::strcpy(str, s);
num_strings++;
}

String::String(){
len = 4;
str = new char[1];
str[0] = '\0';
num_strings ++;
}

String::String(const String &st){
num_strings++;
len = st.len;
str = new char [len + 1];
std::strcpy(str, st.str);
}

String::~String(){
--num_strings;
delete [] str;
}

String & String::operator=(const String &st){
if(this == &st){
return *this;
}
delete [] str;
len = st.len;
str = new char[len + 1];
std::strcpy(str, st.str);
return *this;
}

String & String::operator=(const char *s){
delete [] str;
len = strlen(s);
str = new char[len + 1];
std::strcpy(str, s);
return *this;
}

char & String::operator[](int i){
return str[i];
}

const char & String::operator[](int i)const{
return str[i];
}

bool operator < (const String &st1, const String &st2){
return (std::strcmp(st1.str, st2.str));
}

bool operator > (const String &st1, const String &st2){
return st2 < st1;
}

bool operator == (const String &st1, const String &st2){
return (std::strcmp(st1.str, st2.str) == 0);
}

ostream & operator >> (istream &is , String &st){
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if(is){
st = temp;
}
while(is && is.get() != '\n'){
continue;
}
return is;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息