C++【String类】String插入单个字符,插入字符串的函数实现
2016-05-30 17:16
741 查看
#include<iostream> #include<stdlib.h> #include<assert.h> using namespace std; class String { public: String(const char* str) :_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, tmp._str); } ~String() { if (_str) { delete[] _str; _size =0; _capacity =0; _str = NULL; } } //插入单个字符 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; } //插入字符串 /*void Insert(size_t pos, const char* 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() << endl; } int main() { Test(); system("pause"); return 0; }
相关文章推荐
- C++【String类】String头插单个字符,头删单个字符的函数实现
- C++【常见面试题】String类的实现,以及深拷贝、浅拷贝问题
- 【笔试常考】C语言:深度剖析strlen,sizeof
- 【C语言】注释不可以嵌套使用的举例
- 【C语言】局部变量、全局变量,局部静态变量,全局静态变量,extern,static的区别
- C/C++(&Java) Volatile关键词深度剖析
- C语言;在终端输入多行信息,找出包含“ould”的行,并打印改行。
- C语言:模拟实现printf,要求功能:print(&quot;ccc\ts!&quot;,&#39;b&#39;,&#39;i&#39;,&#39;t&#39;,&quot;welcome to you&quot;);
- 【C语言】编写冒泡排序,排序一个整形数组。
- 【C语言】reverse_str递归调用函数
- C语言:使用冒泡排序,排序多个字符串(优化)。
- C语言:冒泡法排序一组数,如何优化?
- C语言:调整数组使奇数全部都位于偶数前面。
- C语言:模拟实现memmove
- C语言:模拟实现memcpy
- 【笔试题】C语言:模拟实现strcmp
- 【笔试题】C语言:模拟实现strcat
- C语言:模拟实现strcpy
- 【笔试题】C语言:模拟实现strncmp
- 【笔试题】C语言:模拟实现strncat