码迷,mamicode.com
首页 > 其他好文 > 详细

String类简单实现

时间:2015-04-29 21:31:00      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

原文地址:http://rsljdkt.iteye.com/blog/774188

  1 #include "stdafx.h"
  2 #include "stdlib.h"
  3 #include<iostream>  
  4 using namespace std;  
  5   
  6 class String
  7 {
  8 public: 
  9     String(const char *str = NULL);//默认构造函数
 10     String(const String &str);//拷贝构造函数
 11     ~String();
 12     String operator + (const String &str);//字符串连接
 13     String &operator = (const String &str);//字符串赋值
 14     bool operator == (const String &str);//字符串比较
 15     int Length();//获取字符串长度
 16     friend ostream & operator <<(ostream &o,const String &str);//输出重载
 17     String Substr(int start,int end);//求子串
 18 private:
 19     char *data;
 20 };
 21 
 22 String::String(const char* str)
 23 {
 24     if(str == NULL)
 25     {
 26         data = new char[1];
 27         data[0] = \0;
 28     }
 29     else
 30     {
 31         data = new char[strlen(str)+1];
 32         strcpy(data,str);
 33     }
 34 }
 35 String::String(const String &str)
 36 {
 37     data = new char[strlen(str.data)+1];
 38     strcpy(data,str.data);
 39 }
 40 String::~String()
 41 {
 42     delete [] data;
 43 }
 44 
 45 String String::operator+(const String &str)
 46 {
 47     String res;
 48     delete[] res.data;
 49     res.data = new char[strlen(data) + strlen(str.data)+1];
 50     strcpy(res.data,data);
 51     strcpy(res.data+strlen(data),str.data);
 52     return res;
 53 }
 54 
 55 String &String::operator=(const String &str)
 56 {
 57     if(data == str.data)
 58         return *this;
 59     delete []data;
 60     data = new char[strlen(str.data)+1];
 61     strcpy(data,str.data);
 62     return *this;
 63 }
 64 
 65 bool String::operator==(const String &str)
 66 {
 67     return strcmp(data,str.data) == 0;
 68 }
 69 int String::Length()
 70 {
 71     return strlen(data);
 72 }
 73 ostream & operator<<(ostream &o,const String &str)
 74 {
 75     o<<str.data;
 76     return o;
 77 }
 78 
 79 String String::Substr(int s,int e)
 80 {
 81     String res;
 82     delete [] res.data;
 83     res.data = new char[e - s +1];
 84     for(int i=0;i+s < e;i++)
 85     {
 86         res.data[i] = data[s+i];
 87     }
 88     res.data[e-s] = \0;
 89     return res;
 90 }
 91 int _tmain(int argc, _TCHAR* argv[])
 92 {
 93     String s = "abcd";
 94     String t = "abcd";
 95     cout<< s <<(s==t?"==":"!=")<<t<<endl;
 96 
 97     String s1 = "Hello";
 98     String s2 = "China!";
 99     cout<<s1+s2<<endl;
100     cout<<(s1+s2).Substr(0,s1.Length()+s2.Length())<<endl;
101 
102     system("pause");
103     return 0;
104 }

输出结果:

技术分享

 

String类简单实现

标签:

原文地址:http://www.cnblogs.com/nightcatcher/p/4467030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!