#ifndef _string_h#define _string_hclass string{private: char *ptr;public: string():ptr(0){} string(const char *p); string(string &p); ~string();public: string &operator=(const char *p); string &operator=(string &p); string &operator+=(const char *p); string &operator+=(string &p); bool operator==(const char *p); bool operator==(string &p); bool operator!=(const char *p); bool operator!=(string &p); bool operator!(); char operator[](unsigned long i); unsigned long size(); void subString(string &p,int start,int finish); char *getPointer(); int atoi();};#endif
#include <string.h>#include <ctype.h>#include "string.h"string::string(const char *p){ ptr=new char[strlen(p)+1]; strcpy(ptr,p);}string::string(string &p){ ptr=new char[strlen(p.ptr)+1]; strcpy(ptr,p.ptr);}string::~string(){ if(ptr)delete []ptr;}string &string::operator=(const char *p){ if(ptr) { delete []ptr; ptr=0; } if(p) { ptr=new char[strlen(p)+1]; strcpy(ptr,p); } return *this;}string &string::operator=(string &p){ if(ptr) { delete []ptr; ptr=0; } if(p.ptr) { ptr=new char[strlen(p.ptr)+1]; strcpy(ptr,p.ptr); } return *this;}string &string::operator+=(const char *p){ char *tmp; if(p) { if(ptr) { tmp=new char[strlen(ptr)+strlen(p)+1]; strcpy(tmp,ptr); delete []ptr; } else tmp=new char[strlen(p)+1]; strcat(tmp,p); ptr=tmp; } return *this;}string &string::operator+=(string &p){ char *tmp; if(p.ptr) { if(ptr) { tmp=new char[strlen(ptr)+strlen(p.ptr)+1]; strcpy(tmp,ptr); delete []ptr; } else tmp=new char[strlen(p.ptr)+1]; strcat(tmp,p.ptr); ptr=tmp; } return *this;}bool string::operator==(const char *p){ if(p&&ptr) { if(!strcmp(ptr,p))return true; } else if(!(p||ptr))return true; return false;}bool string::operator==(string &p){ if(p.ptr&&ptr) { if(!strcmp(ptr,p.ptr))return true; } else if(!(p.ptr||ptr))return true; return false;}bool string::operator!=(const char *p){ if(p&&ptr) { if(!strcmp(ptr,p))return false; } else if(!(p||ptr))return false; return true;}bool string::operator!=(string &p){ if(p.ptr&&ptr) { if(!strcmp(ptr,p.ptr))return false; } else if(!(p.ptr||ptr))return false; return true;}bool string::operator!(){ if(ptr) { if(*ptr)return false; } return true;}char string::operator[](unsigned long i){ return ptr[i];}unsigned long string::size(){ return strlen(ptr);}void string::subString(string &p,int start,int finish){ if(ptr) { delete []ptr; ptr=0; } ptr=new char[finish-start+2]; memcpy(ptr,&p.ptr[start],finish-start+1); ptr[finish-start+1]=0;}char *string::getPointer(){ return ptr;}int string::atoi(){ char c; int rad; int sum = 0; char *p = ptr; if (p) { if (*p == '0') { if (tolower(*(p + 1)) == 'x') { rad = 16; p += 2; } else { rad = 8; p++; } } else rad = 10; while (isxdigit(*p)) { if (isdigit(*p)) c = *p - '0'; else c =tolower(*p) - 'a' + 10; sum = sum * rad + c; p++; } } return sum;}
引用第4楼zhd32于2007-12-10 22:33发表的 :代码风格需要改进下