1. 程式人生 > >string 類的部分實現

string 類的部分實現

string 類的部分實現

void pushback(char c);尾插

void append(size_t n, char c);尾插 n 個字元 c

string& operator+=(const char* str);追加字串 str

void resize(size_t newsize, char c = char());修改有效字元個數

void reserve(size_t newcapacity);為字串預留空間

size_t find(char c, size_t pos = 0) const;返回字元 c 在字串第一次出現的位置

size_t find(const char* str, size_t pos = 0) const;返回字串在字串第一次出現的位置

string substr(size_t pos, size_t n);擷取從 pos 位置開始的 n 個字元

string& insert(size_t pos, char c); string& insert(size_t pos, const char* str);在 pos 位置插入字元 c 或者字串 str ,並返回該字串的位置

string& erase(size_t pos, size_t len);刪除 pos 位置上的元素,並返回該元素的下一個位置

string& append(const char* str);在字串後面追加 str

string& operator+=(const string& str);在字串後面追加 str

namespace fun
{
	class String
	{
	public:
		String(const char* str = "")
		{
			if (nullptr == str)
			{
				assert(false);
				return;
			}
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}
		String(const String& s)
			: _str(new char[s._capacity + 1])
			, _size(s._size)
			, _capacity(s._capacity)
		{
			strcpy(_str, s._str);
		}
		String& operator=(const String& s)
		{
			if (this != &s)
			{
				char* pStr = new char[s._capacity + 1];
				strcpy(pStr, s._str);

				delete[] _str;
				_str = pStr;
				_size = s._size;
				_capacity = s._capacity;
			}
			return *this;
		}
		~String()
		{
			if (_str)
			{
				delete[] _str;
				_str = nullptr;
			}
		}
	public:
		void pushback(char c)
		{
			if (_size == _capacity)
				reserve(_capacity * 2);
			_str[_size++] = c;
			_str[_size] = '\0';
		}
		void append(size_t n, char c)
		{
			for (size_t i = 0; i < n; ++i)
			{
				pushback(c);
			}
		}
		void reserve(size_t newcapacity)
		{
			//如果新容量大於舊容量,則開闢新空間
			if (newcapacity > _capacity)
			{
				char* str = new char[newcapacity + 1];
				strcpy(str, _str);//把舊空間內容拷貝至新空間
				//釋放舊空間,然後使用新空間
				delete[] _str;
				_str = str;
				_capacity = newcapacity;
			}
		}
		String& operator+=(char c)
		{
			pushback(c);
			return *this;
		}
		String& operator+=(const char* str);//追加字串
		void resize(size_t newsize, char c = char())
		{
			if (newsize > _size)
			{
				//如果 newsize 大於底層空間大小,則需要開闢空間
				if (newsize > _capacity)
				{
					reserve(newsize);
				}
				memset(_str + _size, c, newsize - _size);
			}
			_size = newsize;
			_str[newsize] = '\0';
		}
	private:
		char* _str;
		size_t _capacity;
		size_t _size;
	};
}