#include <iostream> #include <stdlib.h> #include <assert.h>using namespace std;class string{public: string (CONST&NBSP;CHAR*&NBSP;STR) &NBSP;&NBSP;&NBSP;:_STR (New char[strlen (str) + 1]) { _size = strlen (str); _ capacity = _size + 1; strcpy (_str, str ); } string (const String& s) :_str (NULL) { string tmp (S._STR); swap (_STR,&NBSP;TMP._STR); } ~string () { if (_STR) { delete[] _str; _size =0; _capacity =0; _str = NULL; } } //inserts a single character void insert (char ch, size_t POS) { assert (pos <= _size) ; checkcapacility (); size_t begin = _size; while (begin >= pos) { _str[begin + 1] = _str[begin]; begin--; } _str[pos] = ch; ++_size; } //Insert String /*void insert (SIZE_T&NBSP;POS,&NBSP;CONST&NBSP;CHAR*&NBSP;S1) { assert (pos <= _size); int len = strlen (S1); cHeckcapacility (_size+len+1); size_t begin = _ size; while (Begin >= pos) { _str[ begin + len] = _str[begin]; --begin; } for (int i = 0; i < len;i++) { _str[pos++] = s1[i]; } } Char* cstr () { return _str; }privaTe: void checkcapacility (Int needlen) { if (needlen > = _capacity) { _capacity = needlen > 2 * _capacity ? Needlen : 2 * _capacity; _str = (char*) realloc (_str, _capacity); } }private: char* _str; int _size; int _capacity;}; Void test () { string s ("helorld,hello bit!"); s.insert (3, "lo w"); cout << s.cstr () &nBsp;<< endl;} Int main () { test (); system ("Pause"); return 0;}
C + + "String class" string inserts a single character, the function implementation of inserting a string