★ C++基础篇 ★ string类

Ciallo~(∠・ω< )⌒☆ ~ 今天,我将继续和大家一起学习C++基础篇第五章----string类 ~

目录

一  string类的引入

二  string类的构造函数

三  string元素获取

四  auto和范围for

4.1 auto关键字

4.2 范围for

五  string类对象的容量操作

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

6.1 用下标 + [ ] 遍历

6.2 迭代器遍历(通用)

6.3 范围for

七  string类对象的修改操作

八  string类非成员函数

九  vs和g++下string结构的说明

9.1 vs下string的结构

9.2 g++下string的结构

一  string类的引入

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

        在OJ中,有关字符串的题目基本以string类的形式出现,而且在常规工作中,为了简单、方便、快捷,基本都使用string类,很少有人去使用C库中的字符串操作函数。

        在使用string类时,必须包含:

#include<string>
using namespace std;

        string类的文档:string - C++ Reference (cplusplus.com)

二  string类的构造函数

以上三个蓝色箭头是最常用的接口

string()构造空的string类对象,即空字符串
string(const char* s)用C-string来构造string类对象
string(const string&s)拷贝构造函数
string s1;              // 构造空的string类对象s1
string s2("椎名澄岚");   // 用C格式字符串构造string类对象s2
string s3(s2);          // 拷贝构造s3

不常用的:

  • string (const string& str, size_t pos, size_t len = npos);
    把str从pos位置拷贝len个字符到一个字符串
  • string (const char* s, size_t n);
    把s字符串的前n个字符拷贝到一个字符串
    
  • string (size_t n, char c);
    把n个字符换成c字符

析构函数 ~string() 自动调用没什么好讲的 :)

三  string元素获取

  • operator[ ]
  • 获取字符串第n个字符的引用:
string s2 = " hello zmcl!";
s2[0] = 'c'; // 把第一个字符换成c
cout << s2 << endl;

  [ ]发生越界会触发断言

  • at
  • 返回字符串中位置 pos 处的字符的引用

   at 发生越界会抛异常

四  auto和范围for

4.1 auto关键字

  • 在早期C/C++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量,后来这个不重要了。C++11中,标准委员会变废为宝赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得
  • 用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&
  • 当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。
  • auto不能作为函数的参数,可以做返回值,但是建议谨慎使用
  • auto不能直接用来声明数组

auto的用武之地:简化代码,替换长类型:

std::map<std::string, std::string>::iterator it = dict.begin();
auto it = dict.begin(); 

查看类型的方法:

int a = 10;
cout << typeid(a).name() << endl; // 会输出int

4.2 范围for

  • 对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此C++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。
  • 范围for可以作用到数组和容器对象上进行遍历
  • 范围for的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。
int array[] = { 1, 2, 3, 4, 5 };

// C++98的遍历
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
	array[i] *= 2;
}
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
	cout << array[i] << endl;
}

// C++11的遍历
for (auto& e : array)
{
	e *= 2;
}
for (auto e : array)
{
	cout << e << " " << endl;
}

五  string类对象的容量操作

size返回字符串有效字符长度
length返回字符串有效字符长度
capacity返回空间总大小
empty检测字符串释放为空串,是返回true,否则返回false
clear清空有效字符
reserve为字符串预留空间**
resize将有效字符的个数该成n个,多出的空间用字符c填充

max_size

返回字符串的最大大小

shrink_to_fit

请求字符串减小其容量以适合其大小

注意:

  • size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()
  • clear()只是将string中有效字符清空,不改变底层空间大小。
  • 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 res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserver不会改变容量大小。实际开的空间会比参数大。
  • capacity()的值不包含“ \0 ”;

测试扩容:

void TestPushBack()
{
	string s;
	size_t sz = s.capacity();
	cout << "capacity changed:> " << sz << '\n';
	cout << "making s grow:> \n";
	for (int i = 0; i < 100; i++)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed:> " << sz << '\n';
		}
	}
}
capacity changed:> 15
making s grow:>
capacity changed:> 31
capacity changed:> 47
capacity changed:> 70
capacity changed:> 105

由此可见,vs2022在扩容时第一次2倍扩,后1.5倍扩。(不同编译器结果不同)

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

6.1 用下标 + [ ] 遍历

string s1 = " hello zmcl!";
for (size_t i = 0; i < s1.size(); i++) // 遍历字符串打印
{
	cout << s1[i] << " ";
}
cout << endl;

6.2 迭代器遍历(通用)

string s1 = " hello zmcl!";
string::iterator it = s1.begin();
while (it != s1.end())
{
	cout << *it << " ";
	++it;
}
cout << endl;
  • 用迭代器 iterator 前需要加类域,此时为string。
  • 迭代器 iterator 用法和指针类似,但不是指针
  • 迭代器的名称随意,上程序为 it 。
begin()获取第一个字符的迭代器
end() 获取最后一个字符下一个位置的迭代器(“ \0 ”)
rbegin()获取第一个字符前一个位置的迭代器
rend()获取最后一个字符的迭代器

当需要反向遍历时:

string::reverse_iterator rit = s1.rbegin();
while (rit != s1.rend())
{
	cout << *rit << " ";
	++rit;  // 此时++是往回走的
}
cout << endl;

6.3 范围for

string s1 = " hello zmcl!";
for (auto ch : s1)
{
	cout << ch << " ";
}
cout << endl;
  • 迭代器遍历会修改原字符串,范围for想要修改原字符串需要加引用:
for (auto& ch : s1)

七  string类对象的修改操作

push_back在字符串后尾插字符c
append在字符串后追加一个字符串
operator+= (重点)在字符串后追加字符串str
insert插(谨慎使用,效率低)
erase
replace替换
swap交换
void testStrings()
{
	string s1("ciallo zmcl");
	s1.push_back('!');
	s1.append("ye");
	cout << s1 << endl; // ciallo zmcl!ye

	string s2("ial zmzz");
	s2 += " ohhh";
	s2.insert(0, "C"); // Cial zmzz ohhh 头插
	s2.insert(4, "lo"); // Ciallo zmzz ohhh 在下标4位置插
	cout << s2 << endl; 

	string s3("MahiruShiina");
	s3.erase(0, 6); // Shiina 从0开始删6个
	s3.erase(s3.begin()); // hiina 头删
	s3.erase(--s3.end()); // hiin 尾删
	s3.erase(s3.size() - 1, 1); // hii 尾删
	cout << s3 << endl; 
}
void testStrings2()
{
	string s1("Ciallo zmcl");
	s1.replace(6, 1, "--"); // Ciallo--zmcl 下标6处用“--”替换1个字符
	cout << s1 << endl;

	// 把每个空格变为 -
	string s2("C i a l l o z m c l"); // 此方法效率低
	size_t pos = s2.find(' '); // 找空格
	while (pos != string::npos) // 找到底
	{
		s2.replace(pos, 1, "-");
		pos = s2.find(' ', pos + 2); // 从pos+2开始找空格
	}
	cout << s2 << endl; // C-i-a-l-l-o-z-m-c-l

	string s3("C i a l l o z m c l"); // 此方法效率高
	string tmp;
	for (auto ch : s3)
	{
		if (ch == ' ')
			tmp += '-';
		else
			tmp += ch;
	}
	s3.swap(tmp); // 交换 s3 和 tmp 指针
	cout << s3 << endl; // C-i-a-l-l-o-z-m-c-l
}
c_str(重点)返回C格式字符串(为了兼容C语言)
find查找
refind到着找
substr查找子串
find_first_of在字符串中查找字符
find_last_of从末尾查找字符串中的字符
void testStrings3()
{
	string s1("zmcl.cpp.zip");
	size_t pos1 = s1.find('.');
	string ss1 = s1.substr(pos1);// 从pos1位置起取子串
	cout << ss1 << endl; // .cpp.zip

	string s2("zmcl.cpp.zip");
	size_t pos2 = s2.rfind('.'); // 倒着找
	string ss2 = s2.substr(pos2);
	cout << ss2 << endl; // .zip
}

八  string类非成员函数

operator+尽量少用,因为传值返回,导致深拷贝效率低
operator>> (重点)输入运算符重载
operator<< (重点)输出运算符重载
getline (重点)获取一行字符串
relational operators (重点)大小比较

九  vs和g++下string结构的说明

注意:下述结构是在32位平台下进行验证,32位平台下指针占4个字节。

9.1 vs下string的结构

 先是有一个联合体,联合体用来定义 string中字符串的存储空间:

  • 当字符串长度小于16时,使用内部固定的字符数组来存放
  • 当字符串长度大于等于16时,从上开辟空间
union _Bxty
{   
    // storage for small buffer or pointer to larger one
    value_type _Buf[_BUF_SIZE];
    pointer _Ptr;
    char _Alias[_BUF_SIZE]; // to permit aliasing
} _Bx;

        大多数情况下字符串的长度都小于16,那string对象创建好之后,内部已经有了16个字符数组的固定空间,不需要通过堆创建,效率高。

其次:还有一个size_t字段保存字符串长度,一个size_t字段保存从堆上开辟空间总的容量。

最后:还有一个指针做一些其他事情。

共占16+4+4+4=28个字节

9.2 g++下string的结构

        G++下,string是通过写时拷贝实现的,string对象总共占4个字节,内部只包含了一个指针,该指针将来指向一块堆空间,内部包含了如下字段: 空间总大小 字符串有效长度 引用计数 指向堆空间的指针,用来存储字符串。

struct _Rep_base
{
    size_type               _M_length;
    size_type               _M_capacity;
    _Atomic_word            _M_refcount;
};

~ 完 ~

  • 49
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值