C++总结篇(3)String类

string是表示字符串的字符串类,该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string。不能操作多字节或者变长字符的序列。 在使用string类时,必须包含#include头文件以及using namespace std标准空间。

1.常见string类容量操作接口:

  1. size():返回字符串的有效长度
  2. size():length():返回字符串的有效长度,作用于size()相同
  3. capacity(): 返回空间总大小
  4. empty(): 检测字符串释放为空串,是返回true,否则返回false
  5. clear(): 清空有效字符
  6. resize(n):将有效字符的个数该成n个

如例:

void test(string &s)
{
	cout << s.size() << endl;  //字符串的有效长度
	cout << s.length() << endl;//字符串的有效长度
	cout << s.capacity() << endl;//空间的总大小
	cout << s.empty() << endl;//检测字符串是否为空串,是则返回true,反之返回false
	cout << s << endl;
	cout << endl;
	s.resize(3);//将字符串的有限个数改为3个
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s << endl;
	cout << endl;
	s.clear();//清空字符串
	cout << s.empty() << endl;
	cout << s << endl;
}

2.String类对象访问及遍历操作:

  1. operator[]:返回pos位置的字符,const string类对象调用
  2. begin+ end:begin获取第一个字符的迭代器+ end获取最后一个字符下一个位置的迭代器(从前往后打印)
  3. rbegin + rend:begin获取最后一个字符的迭代器 + end获取第一个字符钱啊一个位置的迭代器(从后往前打印)

如例:

void test(string &s)
{
	cout << s.operator[](0) << endl;//返回位置0处的字符
	string::iterator it = s.begin();//获取第一个字符的迭代器
	while (it != s.end())//直到与最后一个字符下一位置的迭代器相等则跳出循环
	{
		cout << *it << endl;
		it++;
	}
	string::reverse_iterator rit = s.rbegin(); //可抽象理解为获取第一个字符的迭代器
	while (rit != s.rend())//可抽象理解为直到与最后一个字符下一位置的迭代器相等则跳出循环
	{
		cout << *rit << endl;
		rit++;
	}
		
}

3.String类对象修改操作:

  1. push_back(‘c’): 在字符串后尾插字符c
  2. append(“world”): 在字符串后追加一个字符串
  3. operator+=(str): 在字符串后追加字符串str c_str(): 返回C格式字符串
  4. find(‘c’,pos):从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
  5. rfind(‘c’,pos):从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
  6. substr(pos,n):在str中从pos位置开始,截取n个字符,然后将其返回

如例:

void test(string &s)
{
	s.push_back('c');//尾插一个字符'c'
	cout << s << endl;
	s.pop_back();//尾删一个字符
	cout << s << endl;
	s.append(" world");//在字符串后追加一个字符串" world"
	cout << s << endl;
	char str[] = "!!!";
	s.operator+=(str);//在字符串后追加一个字符串str
	cout << s.c_str()<<endl;//以c格式打印字符串
	cout << s.find('o', 5)<<endl;//从位置5处向后查找字符'o'并返回其位置
	cout << s.rfind('o', 5) << endl;//从位置5处向前查找字符'o'并返回其位置
	cout << s.substr(0, 5)<<endl;//截取位置0到位置5处的字符串
}

4.string模拟实现

class String
{
public:
	String(const char *str)
	{
		if (str == nullptr)
		{
			return;
		}
		_str = new char[strlen(str) + 1];
		strcpy(_str, str);
	}
	String(const String &str)
		:_str(new char[strlen(str._str)+1])
	{
		strcpy(_str, str._str);
	}
	~String()
	{
		if (_str)
		{
			delete[] _str;
			_str = nullptr;
		}
	}
private:
	char *_str;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值