STL库string模拟实现

在C++中,string是一个类模板,定义在头文件<string>中,提供了对字符串的封装和操作。它实现了动态内存分配和复杂的字符串操作

下面是一些常用的string类成员函数:

  1. 构造函数:可以用于创建和初始化string对象,包括默认构造函数、用C字符串或另一个string对象初始化的构造函数等。

  2. 赋值操作符:可以将另一个string对象、C字符串或字符赋值给当前string对象,包括=、+=、append等操作符。

  3. 访问和修改字符:可以使用下标运算符[]、at()等访问单个字符,也可以使用insert()、erase()等函数插入、删除、替换字符。

  4. 获取字符串长度和容量:可以使用length()、size()获取字符串长度,capacity()获取字符串容量。

  5. 查找和比较字符串:可以使用find()、rfind()、substr()、compare()等函数查找和比较字符串。

  6. 字符串转换:可以使用stoi()、stod()等函数将字符串转换为数字或其他类型,也可以使用to_string()、to_wstring()等函数将数字或其他类型转换为字符串。

  7. 其他操作:还有很多其他的操作,如replace()、swap()、c_str()、empty()等。

需要注意的是,由于string类是动态内存分配的,因此在使用时需要注意内存管理和效率问题。一般来说,string类的效率比char数组和C字符串要低,但是可以使用一些技巧(如reserve()、resize()等)来提高效率。每一次string的复制、取值都由string类负责维护,不用担心复制越界和取值越界等问题。

可通过cplusplus获取更多用法

返回第一个和最后一个位置

iterator begin()
{
	return _str;
}

iterator end()
{
	return _str + _size;
}

构造函数和拷贝构造

string(const char* str = "")//构造函数""里只有\0,\0不是有效字符不算容量空间
{
		_size = strlen(str);
		_capacity = _size;
		_str = new char[_capacity + 1];//+1是最后一个位置存放\0,比如hello是占6个字节
		strcpy(_str, str);
}

string(const string& s)//拷贝构造 strting s2(s1)
			:_str(nullptr)
			,_size(0)
			,_capacity(0)
		{
			string tmp(s._str);
			this->swap(tmp);//this是默认的可不加
		}

析构函数

        ~string()//析构函数
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}

返回容量和有效数据

        size_t size() const
		{
			return _size;
		}

		size_t capacity() const
		{
			return _capacity;
		}

返回C格式字符串

        const char* c_str()//返回C格式字符串
		{
			return _str;
		}

扩容函数和改变容量函数

         void reserve(size_t n)
		{
			if (n > _capacity)//原来的容量不够了
			{
				char* newstr = new char[n + 1];
				strcpy(newstr, _str);//把旧空间拷贝到新空间(\0)
				delete[] _str;//释放旧空间
				_str = newstr;
				_capacity = n;
			}
		}

		void resize(size_t n, char ch = '\0')//将size变成n,但capacity不变
		{
			if (n < _size)//这个实际上是截短字符(串)例:abcde->ab\0
			{
				_str[n] = '\0';
				_size = n;
			}

			else
			{
				if (n > _capacity)//扩容
				{
					reserve(n);
				}
                
                 //插入字符,默认给\0  例:abcde->abcdefgh(或abcde\0\0\0)
				for (size_t i = _size; i < n; ++i)
				{
					_str[i] = ch;
				}

				_size = n;//将size变成n
				_str[_size] = '\0';//最后位置再给一个\0
			}
		}

插入数据和删除数据

        void push_back(char ch)//尾插一个字符
		{
			//if (_size == _capacity)//扩容
			//{
			//	size_t newcapacity = _capacity == 0 ? 2 : _capacity * 2;
			//	reserve(newcapacity);
			//}

			//_str[_size] = ch;//最后一个位置给新字符
			//++_size;
			//_str[_size] = '\0';//再把\0加进去
			
			insert(_size, ch);//复用

		}

		void append(const char* str)//尾插字符串
		{
			//size_t len = strlen(str);
			//if (_size + len > _capacity)//若原有的空间+新字符串的空间>容量 就要扩容
			//{
			//	reserve(_size + len);
			//}

			//strcpy(_str + _size, str);//从_str + _size的位置开始把新的字符串拷贝进去
			//_size += len;

			insert(_size, str);//复用
		}

		string& operator+=(char ch)//插入字符
		{
			this->push_back(ch);
			return *this;
		}

		string& operator+=(const char* str)//插入字符串,和上面代码构成函数重载
		{
			this->append(str);
			return *this;
		}

		string& insert(size_t pos, char ch)//在pos位置插入一个字符
		{
			assert(pos <= _size);
			if (_size == _capacity)//扩容
			{
				size_t newcapacity = _capacity == 0 ? 2 : _capacity * 2;
		 		reserve(newcapacity);
			}

			int end = _size;
			while (end >= (int)pos)
			{
				_str[end + 1] = _str[end];
				--end;
			}
			_str[pos] = ch;
			++_size;
			return *this;
		}

		string& insert(size_t pos, const char* str)//在pos位置插入一个字符串
		{
			assert(pos <= _size);
			size_t len = strlen(str);
			if (_size + len > _capacity)//若原有的空间+新字符串的空间>容量 就要扩容
			{
				reserve(_size + len);
			}

			int end=_size;
			while (end >= (int)pos)//挪动数据,强制类型转换避免越界
			{
				_str[end + len] = _str[end];
				--end;
			}

			//for (size_t i=0; i < len; ++i)//拷贝
			//{
			//	_str[pos++] = str[i];
			//}

			strncpy(_str + pos, str, len);//用库函数拷贝len个字符,不会拷贝\0
			_size += len;
			return *this;
		}

        string& erase(size_t pos, size_t len = npos)//从pos位置开始删除n个字符
		{
			assert(pos < _size);
			if (len >= _size - pos)//删除刚好n个,超过n或nops个字符
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				size_t i = pos + len;
				while (i <= _size)
				{
					/*_str[i-len] = _str[i];
					++i;*/ //同下

					_str[pos++] = _str[i++];

				}
				_size -= len;
			}

			return *this;
		}

查找

        size_t find(char ch, size_t pos = 0)//寻找字符,返回下标
		{
			for (size_t i = pos; i < _size; ++i)
			{
				if (_str[i] == ch)
				{
					return i;
				}
			}

			return npos;
		}

        size_t find(const char* str, size_t pos = 0)//寻找子字符串
		{
			char* p = strstr(_str, str);
            //C语言中寻找子字符串的库函数,找到了返回首字符的地址,没找到返回nullptr
			if (p == nullptr)//找不到返回npos
			{
				return npos;
			}
			else
				return (p - _str);//找到返回下标
		}

operator运算符重载

        bool operator<(const string& s)
   		{
			int ret = strcmp(_str, s._str);
			return ret < 0;
		}

		bool operator==(const string& s)
		{
			int ret = strcmp(_str, s._str);
			return ret == 0;
		}

		bool operator<=(const string& s)
		{
			return *this < s || *this == s;
		}

		bool operator>(const string& s) 
		{
			return !(*this <= s);
		}

		bool operator>=(const string& s)
		{
			return !(*this < s);
		}

		bool operator!=(const string& s) 
		{
			return !(*this == s);
		}

        char& operator[](size_t i)//返回pos下标的字符
		{
			assert(i < _size);//访问的是有效字符
			return _str[i];
		}

		const char& operator[](size_t i) const
		{
			assert(i < _size);
			return _str[i];
		}


        istream& operator>> (istream& in, string& s) //重载输入
	 {
		while (1)
		{
			char ch;
			//in >> ch;//不能用这个
			ch = in.get();//get()获取一个字符
			if (ch == ' ' || ch == '\n')//getline函数只需要把ch == ' ' 去掉即可
			{
				break;
			}
			else
			{
				s += ch;//复用+=
			}
		}
		return in;
	}


	ostream& operator<<(ostream& out, const string& s)//重载输出
	{
		for (size_t i = 0; i < s.size(); ++i)
		{
			out << s[i];
		}
		return out;
	}

代码整合+测试

namespace LXQ2//模拟实现string
{
	class string
	{
	public:

        //将以上代码拷贝进来
    
    private:
		char* _str;
		size_t _size;//_size是有多少个有效字符
		size_t _capacity;//_capacity是能存多少有效字符
		static size_t npos;
	};
	size_t string::npos = -1;

    void test1()
	{
		string s1;
		string s2("hello");
		cout << s1 << endl;
		cout << s2 << endl;
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;

		for (size_t i = 0; i < s2.size(); ++i)
		{
			s2[i] += 1;
			cout << s2[i] << " ";
		}
		cout << endl;

		string::iterator it2 = s2.begin();
		while (it2 != s2.end())//end返回的是size()+1的位置
		{
			*it2 -= 1;
			cout << *it2 << " ";
			++(it2);
		}
		cout << endl;

		for (auto e : s2)//会被编译器替换为迭代器
		{
			cout << e << " ";
		}
		cout << endl;
	}

	void test2()
	{
		string s1("hello");
		cout << s1 << endl;
		s1.push_back(' ');
		s1.push_back('8');
		cout << s1 << endl;
		s1.push_back('j');
		s1.append(" gvgger25698gergergherhyr154169");
		cout << s1 << endl;
		s1 += 'd';
		s1 += "6546546gdg";

		cout << s1 << endl;
	}

	void test3()
	{
		string s1("hello");
		s1.insert(1, 'g');
		s1.insert(0, "60000");
		cout << s1 << endl;
		s1 += "666gfjg";
		cout << s1 << endl;

		/*string s2("hello");
		s2.reserve(10);
		cout << s2 << endl;
		cout << s2.size() << endl;
		cout << s2.capacity() << endl << endl;;

		s2.resize(8, 'x');
		cout << s2 << endl;
		cout << s2.size() << endl;
		cout << s2.capacity() << endl << endl;;

		s2.resize(18, 'a');
		cout << s2 << endl;
		cout << s2.size() << endl;
		cout << s2.capacity() << endl << endl;;

		s2.resize(2);
		cout << s2 << endl;
		cout << s2.size() << endl;
		cout << s2.capacity() << endl;*/
	}

	void test4()
	{
		string s1("helloworld");
		s1.erase(5, 2);
		cout << s1 << endl;
		s1.erase(5, 4);
		cout << s1 << endl;


		string s2("abcdefg");
		cout << s2.find("def") << endl;
		cout << s2.find("defx") << endl;

	}

	void test5()
	{
		string s1("abc");
		s1.insert(1,'c');
		cout << s1 << endl;
		string s2=s1.insert(3,"jkgdrgrhj000");
		cout << s2 << endl;
	}

}

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值