模板初阶的补充和string一些函数的用法

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

世上有两种耀眼的光芒,一种是正在升起的太阳,一种是正在努力学习编程的你!一个爱学编程的人。各位看官,我衷心的希望这篇博客能对你们有所帮助,同时也希望各位看官能对我的文章给与点评,希望我们能够携手共同促进进步,在编程的道路上越走越远!


提示:以下是本篇文章正文内容,下面案例可供参考

模板初阶的补充

一、C语言中的字符串

C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数, 但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。

二、标准库中的string类

2.1 string类(了解)

string类的文档介绍

  1. 字符串是表示字符序列的类
  2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
  3. string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型(关于模板的更多信 息,请参阅basic_string)。
  4. string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits 和allocator作为basic_string的默认参数(根于更多的模板信息请参考basic_string)。
  5. 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个 类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。

总结:

  1. string是表示字符串的字符串类
  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
  3. string在底层实际是:basic_string模板类的别名,typedef basic_string string;
  4. 不能操作多字节或者变长字符的序列。

在使用string类时,必须包含#include头文件以及using namespace std;

2.2 string类的常用接口说明(注意下面我只讲解最常用的接口)

1. string类对象的常见构造

constructor(构造函数名称)功能说明
string() (重点)构造空的string类对象,即空字符串
string(const char* s) (重点)用C-string来构造string类对象
string(size_t n, char c)string类对象中包含n个字符c
string(const string&s) (重点)拷贝构造函数
string (const string& str, size_t pos, size_t len = npos);
//在str字符串中,从pos位置开始,拷贝len个字符的长度
// npos:是-1,因为类型是无符号整型,所以是最大的整数
void test_string1()
{
	string s0;
	string s1("hello world");
	string s2(s1);//拷贝构造
	string s3(s1, 5, 3);
	string s4(s1, 5, 10);
	string s5(s1, 5);

	cout << s0 << endl;
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << s5 << endl;

	string s6(10, '#');
	cout << s6 << endl;

	s0 = s6;
	cout << s0 << endl;
}

int main()
{
	test_string1();

	return 0;
}

2.遍历string类类型的字符数组

方法一:下标 + [ ]

void test_string2()
{
	string s1("hello world");

	//遍历string类类型的字符数组:
	// 方法一:下标+[]   size:返回有多少个字符
	for (size_t i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";//这两个是一样的
		//cout << s1.operator[](i) << " ";//返回第i个位置的字符
	}
	cout << endl;

	for (size_t i = 0; i < s1.size(); i++)
	{
		s1[i]++;//还可以对pos位置的字符进行修改
	}
	cout << endl;

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

	string s3("hello world");
	s3[0]++;
	cout << s3 << endl;

	cout << s3.size() << endl;
	cout << s3.capacity() << endl;
}

int main()
{
	test_string2();

	return 0;
}

方法二:迭代器

void test_string2()
{
	string s3("hello world");
	s3[0]++;
	cout << s3 << endl;

    //方法二:迭代器
	string::iterator it3 = s3.begin();//begin:获取第一个字符的位置
	while (it3 != s3.end())//end:获取最后一个字符的下一个位置(是左闭右开的格式)
	{
		cout << *it3 << " ";
		++it3;
	}
	cout << endl;

	it3 = s3.begin();
	while (it3 != s3.end())
	{
		*it3 -= 3;
		++it3;
	}
	cout << endl;

	cout << typeid(it3).name() << endl;//typeid:查看一个对象的类型
}

int main()
{
	test_string2();

	return 0;
}

方法三:范围for循环

void test_string2()
{
	string s3("hello world");
	s3[0]++;
	cout << s3 << endl;

    // 底层就是迭代器
    for (auto e : s3)
    {
	   cout << e << " ";
    }
    cout << endl;
}

int main()
{
	test_string2();

	return 0;
}

3.反向迭代器

void test_string3()
{
	string s1("hello world");
	//反向迭代器
	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;

	// 可读可写
	string::iterator it2 = s1.begin();
	while (it2 != s1.end())
	{
		*it2 += 3;

		cout << *it2 << " ";
		++it2;
	}
	cout << endl;

	// 只读
	const string s3("hello world");
	string::const_iterator it3 = s3.begin();
	while (it3 != s3.end())
	{
		// *it3 += 3;

		cout << *it3 << " ";
		++it3;
	}
	cout << endl;

	// const_reverse_iterator
}

int main()
{
	test_string3();

	return 0;
}

4. string类对象的容量操作

函数名称功能说明
size (重点)返回字符串有效字符长度
length返回字符串有效字符长度
capacity返回空间总大小
empty (重点)检测字符串释放为空串,是返回true,否则返回false
clear (重点)清空有效字符
reserve (重点)为字符串预留空间**
resize (重点)将有效字符的个数改成n个,多出的空间用字符c填充

string容量相关方法使用代码演示

注意:

  1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一 致,一般情况下基本都是用size()。
  2. clear()只是将string中有效字符清空,不改变底层空间大小。
  3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
  4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于 string的底层空间总大小时,reserver不会改变容量大小。

先来看 reserve(预留空间) 和 clear(清除数据) 操作:

// reserve // 保留
// reverse // 反转 翻转
void test_string4()
{
	string s1("hello worldxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
	cout << s1.size() << endl;
	cout << s1.length() << endl;

	cout << s1.max_size() << endl;
	cout << s1.capacity() << endl;

	// 查看扩容机制
	string s;
	s.reserve(100);//提前保留100个容量,有可能比100个容量多(它是手动扩容)

	size_t sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';//第一次显示堆区上capacity空间的大小
	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		s.push_back('c');//如果一直尾插到capacity空间的大小不够用的话,capacity的大小会扩大(它是自动扩容)
		if (sz != s.capacity())//新的capacity大小与旧的capacity大小的比较
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}

	cout << s1 << endl;
	cout << s1.capacity() << endl;
	cout << s1.size() << endl;


	s1.clear();//clear:清理数据的,不回收空间
	cout << s1 << endl;
	cout << s1.capacity() << endl;
	cout << s1.size() << endl;

	// 缩容
	s1.shrink_to_fit();
	cout << s1.capacity() << endl;
	cout << s1.size() << endl;
}

int main()
{
	test_string4();

	return 0;
}

再来看 resize 的操作:

void test_string5()
{
	string s1("hello worldxxxxxx");
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;

	// 比当前capacity大才会扩容
	s1.reserve(200);//reserve:改变的容量;resize:改变的size
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
	cout << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" << endl;

	string s2("hello worldxxxxxx");
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(10);//保留前10个数据

	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(20);//size < 20 < capacity;保留了字符串,剩下的默认用'\0'来补充

	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(100, 'x');// capacity < 100;扩容并插入'x'

	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;
}

int main()
{
	test_string5();

	return 0;
}

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

函数名称功能说明
operator [] (重点)返回pos位置的字符,const string类对象调用
begin + endbegin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭 代器
rbegin + rendbegin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭 代器
范围forC++11支持更简洁的范围for的新遍历方式

string元素访问及遍历代码演示

6. string类对象的修改操作

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

string中插入和查找等使用代码演示

注意:

  1. 在string尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c'三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
  2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。
void test_string7()
{
	string s1("xhello world");
	s1.push_back('!');
	cout << s1 << endl;

	s1.append("hello bit");
	cout << s1 << endl;

	s1.append(10, 'x');
	cout << s1 << endl;

	string s2("  apple ");
	//s1.append(s2);
	//cout << s1 << endl;
	s1.append(++s2.begin(), --s2.end());
	cout << s1 << endl;

	string s3("hello world");
	s3 += ' ';
	s3 += "apple";
	cout << s3 << endl;
}

int main()
{
	test_string7();

	return 0;
}

insert 、 erase 和 replace 的操作:

void test_string8()
{
	string s1("xhello world");
	cout << s1 << endl;

	s1.assign(" xxxxx");//assign:覆盖字符串的操作
	cout << s1 << endl;

	s1.insert(0, "yyyy");//在pos位置之前插入
	cout << s1 << endl;

	s1.erase(5, 3);//从第5个位置开始,向后删除3个字符
	cout << s1 << endl;

	s1.erase();//删除字符串
	cout << s1 << endl;

	string s2("hello world hello bit");
	/*s2.replace(5, 1, "20%");//从第5个位置开始,替换一个字符为%20
	cout << s2 << endl;*/

	/*size_t pos = s2.find(' ');
	while (pos != string::npos)
	{
		s2.replace(pos, 1, "20%");
		pos = s2.find(' ');//替换完了,继续查找' '字符
	}
	cout << s2 << endl;*/

	// insert/erase/replace
	// 能少用就要少用,因为基本都要挪动数据,效率不高
	string s3;
	s3.reserve(s2.size());//提前保留好空间(s2字符的数量)
	for (auto ch : s2)
	{
		//如果ch变量等于空格,则把字符拷贝下来;否则,就将空格变为%20
		if (ch != ' ')
		{
			s3 += ch;
		}
		else
		{
			s3 += "20%";
		}
	}
	cout << s3 << endl;
	s2.swap(s3);
	cout << s2 << endl;
}

int main()
{
	test_string8();

	return 0;
}


总结

好了,本篇博客到这里就结束了,如果有更好的观点,请及时留言,我会认真观看并学习。
不积硅步,无以至千里;不积小流,无以成江海。

  • 32
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值