C++入门篇7---string类

所谓的string类,其实就是我们所说的字符串,本质和c语言中的字符串数组一样,但是为了更符合C++面向对象的特性,特地将它写成了一个单独的类,方便我们的使用

对其定义有兴趣的可以去看string类的文档介绍,这里就不做过多的介绍了

一、了解string类的接口,及其相关的功能

1.构造函数相关接口

(constructor)函数名称功能说明
string()构造空的string对象,即空字符串
string(const char*s)用C中的字符串构造string类
string(size_t n,char c)用n个c字符创建string对象
string(const string& s)

 拷贝构造  

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s1;
	string s2("hhh");
	string s3(3,'a');
	string s4(s2);
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	return 0;
}

 2. string类对象的容量操作

函数名称功能说明
size返回字符串的有效长度,'\0'除外
length返回字符串的有效长度,和上面一个函数功能一样
capacity返回空间大小(即共能存放多少个字符,'\0'除外)
empty检查字符串是否为空
clear清空字符串,但一般不释放空间,即capacity不变
reserve为字符串预留空间,减少扩容次数
resize将有效字符的个数改成n个,多出来的空间用字符c(传入参数)填充
shrink_to_fit将字符串的capacity缩小至和size一样大,(一般不用)
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s("hello world");
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s.empty() << endl;
	cout << "------------" << endl;

	s.clear();
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s.empty() << endl;
	cout << "------------" << endl;

	s.reserve(100);
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s.empty() << endl;
	cout << "------------" << endl;

	s.resize(10, 'a');
	cout << s << endl;
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s.empty() << endl;
	cout << "------------" << endl;

	return 0;
}

注意:

  • resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时,resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
  • reserve(size_t n = 0)为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。

3.string类对象的访问及遍历操作

函数名称功能说明
operator[ ]返回pos位置的字符
begin+endbegin获取第一个字符的迭代器+end获取最后一个字符下一个位置的迭代器
rbegin+rendrbegin获取最后一个字符的迭代器+rend获取第一个字符前一个位置的迭代器
范围forC++11支持更简洁的范围for的新遍历方式
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string x = "hello world";
	//本质是隐式类型转化+拷贝构造,即调用构造函数创建临时变量,然后拷贝构造,编辑器优化后是一个构造函数
	string::iterator it1 = x.begin();//正向迭代器
	//这里不建议用it1<x.end(),因为string类的迭代器it1++底层是指针后移,
	//但是其他类的迭代器不一定是这样实现的,而!=是通用的
	while (it1 != x.end())
	{
		cout << *it1 << " ";
		++it1;
	}
	cout << endl;

	string::reverse_iterator it2 = x.rbegin();//逆向迭代器
	while (it2 != x.rend())
	{
		cout << *it2 << " ";
		++it2;
	}
	cout << endl;


	for (auto& s : x)//底层实现就是上面的正向迭代器
	{
		cout << s << " ";
	}
    cout << endl;

	for (int i = 0; i < x.size(); i++)
	{
		cout << x[i] << " ";
	}
	const string y = "good game";
	string::const_iterator it3 = y.begin();//具有常属性的对象的迭代器写法
	string::const_reverse_iterator it4 = y.rbegin();
	return 0;
}

4.string类对象的修改操作

函数名称功能说明
push_back在字符串后尾插字符c
append在字符后追加一个字符串
operator+=在字符串后追加字符串/字符
c_str返回C语言格式的字符串
find从字符串pos位置开始往后找字符c,返回该字符在字符串中的下标
rfind从字符串pos位置开始往前找字符c,返回该字符在字符串中的下标
substr在str中从pos位置开始,截取n哥字符,然后将其返回

下面是一些测试用例,可以去自己调试调试,当然还有写其他的用法没写,有兴趣可以去查查文档,一般来说下面的用法就够用了

void test1()
{
	string x;
	x.push_back('a');
	x.push_back('b');
	x.push_back('c');
	cout << x << endl;
	x.append("def");
	cout << x << endl;
	x += 'e';
	cout << x << endl;
	x += "fgh";
	cout << x << endl;
}

void test2()
{
	string x = "test.txt";
	FILE* fp = fopen(x.c_str(), "w");
	//...
	//当我们调用C语言中的一些需要类似char*参数的相关接口时,
	//我们就需要将string转成C语言中的字符串,进行调用
	fclose(fp);
}

void test3()
{
	string s = "hello world";
	size_t p = s.find('l');//默认从起始位置开始找
	if (p != string::npos)//没找到时会返回npos
		cout << p << " " << s[p] << endl;

	p = s.find('l',5);//从下标为5的位置开始找
	if (p != string::npos)
		cout << p << " " << s[p] << endl;

	p = s.find("world");//默认从其实位置开始找
	if (p != string::npos)
		cout << p << " " << s[p] << endl;

	p=s.find("world",3);//从下标为3的位置开始找
	if (p != string::npos)
		cout << p << " " << s[p] << endl;

	p = s.find("word", 1, 2);//从下标1开始找和word前两个字符匹配的地方
	if (p != string::npos)
		cout << p << " " << s[p] << endl;

	//string x = "word";
	//p = s.find(x, 1);//从下标1开始在s中找x,也可以默认从0开始
	//rfind用法和find用法一样
}

void test4()
{
	string x = "you are right";
	cout << x.substr(0, 3) << endl;//从下标0开始往后取3个字符返回,返回类型是string
	cout << x.substr(4, 3) << endl;//从下标4开始往后取3个字符返回,返回类型是string
	cout << x.substr(8, 5) << endl;//从下标8开始往后取5个字符返回,返回类型是string
}

int main()
{
	//test1();
	//test3();
	//test4();
	return 0;
}

5.string类的非成员函数介绍

函数名称功能说明
operator++运算符重载
operator>>输入运算符重载
operator<<输出运算符重载
getline获取一行字符串

上面的函数就不一一枚举用法了,基本一看就懂,不确定的可以去查查文档,或者自己调试看看

总结:string相关的接口一般就是这些,还有些不常用没写,如果感兴趣可以去查查文档,学完后可以去找些题目来练练,其实很快就能记住string的常用接口用法

二、实现string类的常用接口

#include<iostream>
using namespace std;
#include<assert.h>
namespace zxws
{
	class string
	{
	public:
		string(const char* str = "")
			:_size(strlen(str))
			, _capacity(strlen(str))
		{
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		void swap(string& tmp)
		{
			std::swap(_str, tmp._str);
			std::swap(_size, tmp._size);
			std::swap(_capacity, tmp._capacity);
		}

		string(const string& s)
			:_str(nullptr)
			,_size(0)
			,_capacity(0)
		{
			string tmp(s._str);
			swap(tmp);
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}

		const char* c_str() const
		{
			return _str;
		}

		string& operator=(string tmp)
		{
			swap(tmp);
			return *this;
		}

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

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

		size_t size() const
		{
			return _size;
		}

		size_t capacity()const
		{
			return _capacity;
		}

		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}

		void resize(size_t n,char x = '\0')
		{
			if (n <= _size)
			{
				_str[n] = '\0';
				_size = n;
			}
			else
			{
				reserve(n);
				for(int i=_size;i<n;i++)
                    _str[i]=x;
                _str[n]='\0';
                _size=n;
			}
		}

		void push_back(char x)
		{
			if (_size == _capacity)
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			_str[_size++] = x;
			_str[_size] = '\0';
		}

		void append(const char* str)
		{
			size_t len = strlen(str);
			if (_size + len > _capacity)
				reserve(_size + len);
			strcpy(_str+_size, str);
			_size += len;
		}

		void append(size_t n, char x)
		{
			reserve(_size + n);
			while (n--)
			{
				push_back(x);
			}
		}

		string& operator+=(char x)
		{
			push_back(x);
			return *this;
		}

		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}

		size_t find(char x, size_t pos = 0)
		{
			assert(pos < _size);
			for (size_t i = pos; i < _size; i++)
			{
				if (x == _str[pos])
					return i;
			}
			return npos;
		}

		size_t find(const char* str, size_t pos = 0)
		{
			assert(pos < _size);
			char* p = strstr(_str, str);
			return p == nullptr ? npos : p - _str;
		}

		void insert(size_t pos, char x)
		{
			assert(pos <= _size);
			reserve(_size + 1);
			for (size_t i = _size + 1; i > pos; i--)
			{
				_str[i] = _str[i - 1];
			}
			_str[pos] = x;
			_size++;
		}

		void insert(size_t pos, const char* str)
		{
			assert(pos < _size);
			size_t len = strlen(str);
			reserve(_size + len);
			for (size_t i =_size+1,j=_size+len ; i > pos; i--,j--)
			{
				_str[j] = _str[i - 1];
			}
			strncpy(_str + pos, str, len);
			_size += len;
		}

		void erase(size_t pos,size_t n=npos)
		{
			assert(pos < _size);
			if (n == npos || pos + n >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				for (size_t i = pos, j = pos + n; j <= _size; i++, j++)
				{
					_str[i] = _str[j];
				}
				_size -= n;
			}
		}

		typedef char* iterator;
		typedef const char* const_iterator;

		iterator begin()
		{
			return _str;
		}
		
		const_iterator begin() const
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		const_iterator end() const
		{
			return _str + _size;
		}

		string substr(size_t pos,size_t n=npos) const
		{
			assert(pos < _size);
			string tmp;
			size_t end = pos + n;
			if (n == npos || pos + n >= _size)
			{
				n = _size - pos;
				end = _size;
			}
			tmp.reserve(n);
			for (size_t i = pos; i < end; i++)
				tmp += _str[i];
			return tmp;
		}

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

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

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

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

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

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

		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}

	private:
		char* _str;
		size_t _size;
		size_t _capacity;
		const static size_t npos;

		friend ostream& operator<<(ostream& cout, const string& s);
		friend istream& operator>>(istream& cin, const string& s);
	};
	const size_t string::npos = -1;

	ostream& operator<<(ostream& cout, const string& s)
	{
		for (size_t i = 0; i < s._size; i++)
		{
			cout << s[i];
		}
		return cout;
	}

	istream& operator>>(istream& cin, string& s)
	{
		s.clear();
		char buff[129] = { 0 };
		char x = getchar();
		int i = 0;
		while (x == ' ' || x == '\n')
			x = getchar();
		while (x != '\n' && x != ' ')
		{
			buff[i++] = x;
			if (i == 128)
			{
				buff[i] = '\0';
				s += buff;
				i = 0;
			}
			x = getchar();
		}
		if (i) {
			buff[i] = '\0';
			s += buff;
		}
		return cin;
	}
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值