【C++之string类】

C++知识string类

前言:
前面篇章学习了C++对于类和对象的认知知识,接下来继续学习,C++的关于string类等知识。
/知识点汇总/

1、String类

1.1、为什么要学习string类?

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

1.2、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.3、string类的小结

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

2、标准库中的string类

3.1、string类的常用接口说明

< string >是C++标准程序库中的一个头文件,定义了C++标准中的字符串的基本模板类std::basic_string及相关的模板类实例
其中的string是以char作为模板参数的模板类实例,把字符串的内存管理责任由string负责而不是由编程者负责,大大减轻了C语言风格的字符串的麻烦。
比如一些string类对象的常见构造:

string()   //构造空的string类对象,即空字符串
string(const char* s)   //用C-string来构造string类对象
string(size_t n, char c)    //string类对象中包含n个字符c
string(const string&s)   //拷贝构造函数
//string类对象的常见赋值重载std::string::operator=
string& operator= (const string& str);
string& operator= (const char* s);
string& operator= (char c);

3.2、string类常用接口的应用1

#include <iostream>
using namespace std;
void test_string()
{
	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;

	//赋值重载
	string s7;
	s7 = s5;
	cout << s7 << endl;
}
int main()
{
	test_string();
	return 0;
}

3.3、string类常用接口的应用2

//遍历,下标+[]--->本质是[]运算符重载
std::string::operator[]
//原型:
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;

这里的[ ]具备读写权限

//读
#include <iostream>
using namespace std;
void test_string2()
{
	string s1("hello world");
	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " " ;
		//等价于
		//cout << s1.operator[](i) << " " ;
	}
	cout << endl;
}
int main()
{
	test_string2();
	return 0;
}
//写
#include <iostream>
using namespace std;
void test_string3()
{
	string s1("hello world");
	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";
		//等价于
		//cout << s1.operator[](i) << " " ;
	}
	cout << endl;
	for (int i = 0; i < s1.size(); i++)
	{
		cout << ++s1[i] << " ";
	}
	cout << endl;

	//另一个原型,构成函数重载,隐含指针this指针不同,this和const this,并且,const的成员函数为只读
	const string s2("hello world!");
	//s2[0]++;//error -- const修饰的为只读
	cout << s2 << endl;

	string s3("hello world!");
	s3[0]++;
	cout << s3 << endl;
}
int main()
{
	test_string3();
	return 0;
}

3.4、string类常用接口的应用3

string除了size的遍历方式,还有另外两种遍历方式。

1.iterator迭代器(重点)
2.范围for

#include <iostream>
#include <string>
#include <vector>
#include <list>
using namespace std;
void test_string4()
{
	string s1("hello world");
	for (int i = 0; i < s1.size(); i++)
	{
		cout << s1[i] << " ";
	}
	cout << endl;

	cout << s1.size() << endl;  //C++兼容C语言,所以size同样与strlen一样不包括'\0'标志位
	cout << s1.capacity() << endl;

	string s3("hello world");
	//遍历方式2:iterator迭代器,行为像指针一样的类型对象。
	string::iterator it3 = s3.begin();//首元素地址
	while (it3 != s3.end())//end()取的是最后一个有效字符的下一个位置。即,'\0'
	{
		cout << *it3 << " ";
		++it3;
	}
	cout << endl;
	//打印类型
	cout << typeid(it3).name() << endl;

	//迭代器的优势,迭代器相对于下标+[],它可以解决遍历链表和树的结构。
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);

	vector<int>::iterator vt = v.begin();
	while (vt != v.end())
	{
		cout << *vt << " ";
		++vt;
	}
	cout << endl;

	list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);

	list<int>::iterator it = lt.begin();
	while (it != lt.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	//范围for,遍历容器
	for (auto e : s3)
	{
		cout << e << " ";
	}
	cout << endl;
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;
	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;
}
int main()
{
	test_string4();
	return 0;
}

3.5、string类常用接口的应用4

string类对象的容量操作

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

注意:

  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不会改变容量大小。
#include <iostream>
#include <string>
using namespace std;
void test_string1()
{
	string s1("hello world");

	cout << s1.size() << endl;  //C++兼容C语言,所以size同样与strlen一样不包括'\0'标志位
	cout << s1.capacity() << endl;
	cout << s1.length() << endl;
}
void test_string2()
{
	string s1("hello world");
	//正向迭代器
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	//反向迭代器
	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
}
//std::string::begin
//iterator begin();
//const_iterator begin() const;
void test_string3()
{
	string s1("hello world");
	//正向迭代器 -- 读写
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		*it += 1;//读写
		cout << *it << " ";
		++it;
	}
	cout << endl;
	//反向迭代器 --- 读写
	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		*rit += 1;//读写
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
	//const迭代器 --- 只读
	const string s2("hello world");
	//string s2("hello world");
	//string::iterator cit = s2.begin();
	string::const_iterator cit = s2.begin();
	while (cit != s2.end())
	{
		//*cit += 1;//只读
		cout << *cit << " ";
		++cit;
	}
	cout << endl;
	//const_reverse_iterator迭代器 --- 反向只读
	const string s3("hello world");
	string::const_reverse_iterator rcit = s3.rbegin();
	while (rcit != s3.rend())
	{
		//*cit += 1;//只读
		cout << *rcit << " ";
		++rcit;
	}
	cout << endl;
}

//string类对象的容量操作
void test_string4()
{
	string s1("hello world");
	cout << s1 << endl;
	cout << s1.size() << endl;  //C++兼容C语言,所以size同样与strlen一样不包括'\0'标志位
	cout << s1.capacity() << endl;
	cout << s1.length() << endl;
	cout << s1.max_size() << endl;
	//查看vs扩容机制
	string s;
	size_t sz = s.capacity();
	cout << "capacity changed: " << sz << endl;
	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 << endl;
		}
	}
	//小结:
	//Vs扩容的倍率是以内存对齐的规则进行的,  
	//linux扩容的倍率是以给多少就扩多少的规则进行的,  
	//所以由编译器/环境决定。
	
	//清理数据
	cout << s1 << endl;
	s1.clear();
	cout << s1 << endl;
	cout << s1.size() << endl;  
	cout << s1.capacity() << endl;
	cout << s1.length() << endl;
	//缩容
	s1.shrink_to_fit();//缩至,buffer大小
	cout << s1.capacity() << endl;
	cout << s1.length() << endl;
}
//reserve --- 保留 --->明确大小的扩容 --> 手动
//reverse --- 反转 --->反向迭代器
//resize --- 改变size,也会扩容 --> 自动
//std::string::resize
//void resize (size_t n);
//void resize(size_t n, char c);
void test_string5()
{
	string s1("hello world");
	cout << s1 << endl;
	cout << s1.size() << endl; 
	//s1.reserve(10);
	//s1.reserve(12);
	s1.reserve(30);//扩容
	cout << s1.capacity() << endl;//111
	//小结:适用于,知道所需的空间大小,提前开辟扩容空间。
	//reserve<size ---> 无效
	//size<reserve<capacity ---> 无效
	//reserve>capacity ---> 生效
	cout << "xxxxxxxxxxxxxxxxxx" << endl;

	string s2("hello world");
	cout << s2 << endl;
	cout << s2.size() << endl;//11,size不包括'\0'
	cout << s2.capacity() << endl;//15
	s2.resize(8);
	cout << s2 << endl;
	cout << s2.size() << endl;//8
	cout << s2.capacity() << endl;//15
	//s2.resize(12);//默认'\0'
	s2.resize(12,'a');
	cout << s2 << endl;
	cout << s2.size() << endl;//12
	cout << s2.capacity() << endl;//15
	//s2.resize(30);//默认'\0'
	s2.resize(30, 'A');
	cout << s2 << endl;
	cout << s2.size() << endl;//30
	cout << s2.capacity() << endl;//31 -- 因为capacity包括'\0'.所以实际是31

	//resize<size ---> 删除数据
	//size<resize<capacity ---> 插入数据默认'\0',或指定字符
	//resize>capacity ---> 扩容+插入
}

3.6、string类常用接口的应用5

string类对象的访问操作

operator[] --> 下标+[]
at
back
front

void test_string6()
{
	string s1("hello world");
	cout << s1 << endl;
	cout << s1[6] << endl;
	//等价
	cout << s1.operator[](6) << endl;
	//at与下标+[]基本相同,不同在于对于越界的检查有所不同。
	cout << s1.at(6) << endl;
	//不同在于对于越界的检查有所不同。
	//抛异常捕获验证
	try
	{
		//访问越界的报错反馈不同。
		//s1[15];
		//s1.at(15);
	}
	catch (const exception& e)
	{
		cout << e.what() << endl;
	}
}

3.7、string类常用接口的应用6

string类对象的修改操作

operator+= 重点
append
push_back
assign
insert
erase
replace
swap
pop_back

void test_string7()
{
	string s1("hello world");
	cout << s1 << endl;
	//尾插
	s1.push_back('!');
	cout << s1 << endl;
	//追加/附加字符串
	s1.append("???");
	cout << s1 << endl;
	string s2("  bit ");
	s1.append(s2);
	cout << s1 << endl;
	s1.append(s2,2,1);
	cout << s1 << endl;
	cout << "xxxxxxxxxxxx" << endl;
	//s1.append(s2.begin(), s2.end());//还有迭代器的重载函数的使用形式。
	//并且迭代器的优势,在于可读写
	s1.append(++s2.begin(), --s2.end());
	cout << s1 << endl;
	//相对于前两种,更常用+=
	s2 += 'o';
	s2 += "abc";
	cout << s2 << endl;
	string s3(" hello ");
	s2 += s3;
	cout << s2 << endl;
}

assign --> 赋值、分派、布置、指定

void test_string8()
{
	string s1("hello world");
	cout << s1 << endl;
	s1.assign("abcdef");//覆盖数据,改写为指定内容,可扩容
	cout << s1 << endl;
}

std::string::insert
std::string::erase
std::string::replace
std::string::find

void test_string9()
{
	string s1("hello world");
	cout << s1 << endl;
	//插入
	s1.insert(0,"abcdef ");//覆盖数据,改写为指定内容,可扩容
	cout << s1 << endl;
	//删除
	s1.erase(5,3);
	cout << s1 << endl;
	//替换
	s1.replace(5, 1, "20%");
	cout << s1 << endl;

	cout << "xxxxxxxxxxxxxxxxxxxxx" << endl;

	string s2("hello world hello bit ");
	cout << s2 << endl;
	size_t pos = s2.find(' ');
	//npos
	//如果你指的是npos,那么它是std::string类中的一个静态常量,用于表示未找到子字符串或字符的位置。
	//当使用find()成员函数或其他搜索函数时,如果未找到匹配的子字符串或字符,它们将返回std::string::npos。
	//npos是-1的补码。由于 size_t 是一个无符号整数类型,所以是一个正整数的超大值,超出了任何实际字符串可能具有的长度。
	while (pos != string::npos)
	{
		s2.replace(pos, 1, "20%");
		pos = s2.find(' ');
	}
	cout << s2 << endl;
	cout << s2.size() << endl;
	cout << "xxxxxxxxxxxxxxxxxxxxx" << endl;
	//虽然好用,但是追究底层来说,需要涉及挪动大量的数据,效率不高。
	//那么同样是解决替换空格,可使用+=的思路解决。
	s2.replace(0, 30, "hello world hello bit ");
	cout << s2 << endl;
	string s3;
	s3.reserve(s2.size());
	for (auto ch : s2)
	{
		if (ch != ' ')
		{
			s3 += ch;
		}
		else
		{
			s3 += "20%";
		}
	}
	cout << s3 << endl;
	s2.swap(s3);
	cout << s2 << endl;
}

std::string::c_str
将string字符串转换为C语言的字符数组
等价data
std::string::copy
拷贝string一部分内容到字符数组中

void test_string10()
{
	string s1("hello world");
	cout << s1 << endl;

	string filname("test.cpp");
	FILE* fout = fopen(filname.c_str(), "r");
	//cout << fout << endl;

	const char* str = s1.c_str();
	cout << str << endl;

	//size_t copy(char* s, size_t len, size_t pos = 0) const;
	char ch[10];
	size_t length = s1.copy(ch, 5);
	cout << length << endl;
	ch[length] = '\0';
	cout << ch << endl;
}

将string转回其它类型:stod()

void test_string16()
{
	int i = 1024;
	double d = 11.22;
	//其他类型转string类型
	string s1 = to_string(i);
	cout << s1 << endl;
	string s2 = to_string(d);
	cout << s2 << endl;
	//string转回其他类型
	string s3("66.6");
	double d2 = stod(s3);
	cout << d2 << endl;
}

int main()
{
	test_string16();
	return 0;
}

3.8、string类常用接口的应用7

string运算符重载

void test_string12()
{
	string s1("filename.cpp");
	cout << s1 << endl;

	string s2 = "xxx";//const + char* 会隐式类型转换--》string
	string s3 = "yyy";
	string ret = s3 + s2;
	cout << ret << endl;

	string ss1 = "xxxx" + s2;
	string ss2 = s3 + "xxxx";
	string ret1 = ss1 + "yyyyy";
	string ret2 = ss2 + "yyyyy";
	cout << ret1 << endl;
	cout << ret2 << endl;
}

4、string类编码机制

4.1、编码机制概念

编码机制是一种将信息或数据转换成特定格式或代码的过程。
这个过程的核心目的是方便信息的存储、传输和处理。
编码机制广泛应用于计算机科学、信息论、通信等多个领域。
在计算机科学中,编码机制主要涉及将人类可读的字符(如文字、数字、符号等)转换为计算机能够识别的二进制代码。
这种转换过程称为编码,而反向过程(从二进制代码转换回原始字符)则称为解码。
例如,在ASCII编码中,每个字符都被分配了一个特定的二进制代码,这样计算机就能够理解并处理这些字符。
在通信领域,编码机制用于将模拟信号转换为数字信号,以便在信道中进行传输。
这种转换过程可以提高信号的抗干扰能力,降低传输误差,从而提高通信质量。
常见的编码方式包括差分编码、脉冲编码调制(PCM)等。
此外,编码机制还广泛应用于数据加密、图像处理、音频处理等领域。
例如,在数据加密中,编码机制可以用于保护数据的机密性和完整性;在图像处理中,编码机制可以用于图像的压缩和存储等。
总之,编码机制是一种重要的信息处理方式,它能够将原始信息转换为适合特定应用的格式或代码,从而实现信息的有效存储、传输和处理。

4.2、典型的ASCII编码

全称为American Standard Code for Information Interchange,即美国信息交换标准代码,是基于拉丁字母的一套电脑编码系统。
它主要用于显示现代英语和其他西欧语言,是最通用的信息交换标准,并等同于国际标准ISO/IEC 646。
它划分为两个集合:128个字符的标准ASCII码和附加的128个字符的扩充和ASCII码。
其中,标准ASCII码使用7位二进制数来表示所有的大写和小写字母、数字0到9、标点符号,以及在美式英语中使用的特殊控制字符。
扩充的ASCII码使用8位二进制数,总共可以表示256种可能的字符。
‘0’-- 48
‘a’-- 97
‘A’ – 65
空格 – 32

4.3、unicode万国码

unicode万国码:由统一码联盟开发,标定了计算机领域的编码标准
Unicode(统一码、万国码、单一码)是一种在计算机科学领域广泛使用的字符编码标准。
它解决了传统字符编码方案的局限性,为每种语言中的每个字符设定了统一且唯一的二进制编码,从而满足了跨语言、跨平台的文本转换和处理需求。

4.4、.gbk,GBK编码

gbk,GBK编码主要用于简体中文环境,能够覆盖绝大多数的中文字符,因此在中文环境中得到了广泛应用。
然而,它并不支持繁体中文和其他非中文语言字符,所以在多语言环境中可能不是最佳选择。
GBK(GB2312K)是中华人民共和国全国信息技术标准化技术委员会1995年12月1日制订,于1995年12月15日开始实施的汉字内码扩展规范,
扩展了GB2312标准,共收录了21003个汉字,它分为汉字区和图形符号区,其编码范围是从8140至FEFE(十进制),共划分为86个区号。
其编码范围超过了原GB2312标准,兼容GB2312。

5、string类练习题

5.1、字符串最后一个单词的长度

void test_string13()
{
	string str;
	cout << "请输入一段字符串:>" << endl;
	//cin >> str;
	//注意:cin和scanf一样,默认空格和换行就是结束了输入。

	//方法1:利用getchar()
	char ch = getchar();
	while (ch != '\n')
	{
		str += ch;
		ch = getchar();
	}
	//方法二:std::string::getline
	getline(cin, str);

	size_t pos = str.rfind(' ');
	cout << str.size() - (pos + 1) << endl;
}

5.2、字符串中第一个唯一的字符

void test_string14()
{
	class solution
	{
	public:
		int firstUniqChar(string s)
		{
			int count[26] = { 0 };
			//统计次数
			for (auto ch : s)
			{
				//映射
				count[ch - 'a']++;
			}
			//返回第一个唯一字符
			for (int i = 0; i < s.size(); i++)
			{
				//绝对映射
				if (count[s[i] - 'a'] == 1)
					return i;
			}
			return -1;
		}
	};
	solution str;
	string s = "sgusvbauu";
	int ret = str.firstUniqChar("sgusvbauu");
	cout << s[ret] << endl;
}
  • 23
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值