字符串类 class String

  1 #include<iostream>
  2 #include<string>
  3 #include<stdlib.h>
  4 #include<assert.h>
  5 using namespace std;
  6 
  7 class String{
  8 private:
  9     char *str;
 10     int size;
 11 public:
 12     String(char *s);
 13     ~String();
 14     String operator+(String& s);
 15     String operator=(String& s);
 16     String Substr(int index,int cout);
 17     int Find(char c,int start);
 18 }
 19 
 20 String::String(char *s)
 21 {
 22     size=strlen(s);
 23     str=new char[size+1];
 24     assert(str!='\0');
 25     strcpy(str,s);
 26 }
 27 
 28 String::~String()
 29 {
 30 }
 31 
 32 String String::operator+(String& s)//拼接
 33 {
 34     String temp="\0";
 35     int len;
 36     len=size+s.size;
 37     delete [] temp.str;
 38     temp.str=new char[len+1];
 39     assert(temp.str!=NULL);
 40     temp.size=len;
 41     strcpy(temp.str,str);
 42     strcat(temp.str,s.str);
 43     return temp;
 44 }
 45 
 46 String String::operator=(String& s)//赋值
 47 {
 48     if(size!=s.size)
 49     {
 50         delete[]str;
 51         str=new char[s.size+1];
 52         assert(str!=NULL);
 53         size=s.size;
 54     }
 55     strcpy(str,s.str);
 56     return *this;//返回得到的字符串
 57 }
 58 
 59 String String::Substr(int index,int count)//提取字符串 index开始下表 cout长度
 60 {
 61     int i;
 62     int left=size-index;
 63     String temp=NULL;
 64     if(index>=size) return temp;
 65     if(count>=left) count=left;
 66     delete [] temp.str;
 67     temp.str=new char[count+1];
 68     assert(temp.str!=NULL);
 69     char *p,*q;
 70     p=temp.str;
 71     q=&str[index];
 72     for(int i=0;i<count;i++)
 73         *p++=*q++;
 74     *p='\0';
 75     temp.size=count;
 76     return temp;
 77 }
 78 
 79 int String::Find(char c,int start)
 80 {
 81     int i=start;
 82     assert(i<size);
 83     while(str[i]!='\0'&&str[i]!='c')
 84     {
 85         i++;
 86     }
 87     if(str[i]=='\0')
 88         return -1;
 89     else
 90         return i;
 91 }
 92 
 93 void main()
 94 {
 95     char *s;
 96     s="qweasd123";
 97     String::String(char *s);
 98 
 99     cout<<s;
100     cou<<"12312312";
101 
102 }
原文地址:https://www.cnblogs.com/coder2012/p/2708829.html