#include <iostream>using namespace std; #include <assert.h>class string{ Public: string (char*str= "") { _size = strlen (str); _capacity = _size + 1; _str = new char[_capacity]; strcpy (_str, STR); } ~string () { if (_STR) { delete[]_str; _size = 0; _capacity = 0; _str = Null; } } void pushback (char ch) { checkcapacity (_size+2); _str[_size] = ch; _str[++_size] = '; } void ' Popback () { assert (_size > 0); --_size; _str[_size] = ' }//insert single character void insert (Size_t pos, char ch) { assert ( Pos <= _size); checkcapacity (_size+2); size_t index = _size; while ( Index >= pos) { _str[Index + 1] = _str[Index]; --index; } _str[pos] = ch; _size++; }//inserting a string void insert (SIZE_T&NBSP;POS,&NBSP;CHAR*STR) { assert (pos <= _size); size_t index = _size; int length = strlen (str); checkcapacity (_size+1+length); while (index >= pos) { _str[index + length] = _str[index]; --index; } for (int i = 0; i < length; ++i) { _str[pos + i] = str[i]; } _size += length; }//find a single character size_T find_ch (char ch) { size_t length = strlen (_STR); for (int i = 0; i < length; i++) { if (_str[i] == ch) { return i; } } return -1; }//Find sub-string size_t find_str (const char*sub) { size_t srcsize = _size; size_t subsize = strlen (sub); size_t SrcIndex = 0; while (srcindex <=_size-subsize) { size_t SubIndex = 0; size_t begin = SrcIndex; while (begin < Srcsize &&subindex < subsize &&_str [Begin] == sub[subindex]) { begin++; subindex++; } if (subindex == subsize) { return srcindex; } srcindex++; } return -1; } void erase (Size_t pos) { assert (POS); for (int i = pos; i < _size-1; ++i) { _str[i] = _ str[i + 1]; } _size--; _str[_size] = '; } string &operator+= ( const string& s) { this->insert (_size, &NBSP;S._STR); return *this; } char*cstr () { return _str; }private: void checkcapacity (int needsize) { if (needsize >= _capacity) { _capacity = needsize>2 * _capacity ? needsize:2*_capacity; _str = (char*) realloc (_str, _capacity); } }private: char*_str; int _size; int _capacity;};
This article is from the "printf Return Values" blog, so be sure to keep this source http://10741125.blog.51cto.com/10731125/1754464
C + + String additions and deletions check and change