C++ string类详解

⭐️ string

string 是表示字符串的字符串类,该类的接口与常规容器的接口基本一致,还有一些额外的操作 string 的常规操作,在使用 string 类时,需要使用 #include <string> 以及 using namespace std;

帮助文档:https://cplusplus.com/reference/string/string/string/

🌟 std::string::string 构造函数(constructor)

序号构造函数功能
1️⃣string()默认拷贝:构造空的string类对象,即空字符串,默认第一个字符位置是'\0',为了兼容c
2️⃣string(const string& str)拷贝构造
3️⃣string(const string& str , size_t pos , size_t len = npos)拷贝构造的重载,从字符串 pos 位置开始拷贝,拷贝 len 个字符
4️⃣string(const char * s)使用 c_string 来初始化 string 类对象
5️⃣string(const char * s , size_t n)s 指向的字符串中复制前 n 个字符
6️⃣string(size_t n , char c)使用 nc 字符来填充字符串
7️⃣template <class InputIterator> string (InputIterator first , InputIterator last)复制一个迭代器序列的字符串 [first , last)
#include <iostream>
#include <string>
using namespace std;

int main() {

	string s1;	// 默认构造 第一个字符是 `\0`
	cout << s1 << endl;

	/*
		调用构造本身的写法应该是:string s2("hello world");
		但是为什么可以这样写呢? string s2 = "hello world";
		因为当构造函数是单参的时候,是支持隐式类型转换的。这里本质上先构造再拷贝构造,但是编译器
		通常会优化为直接构造。若不希望隐式类型的转换可以在构造函数前添加 explicit 关键字
	*/
	string s2 = "hello world"; // 使用c字符串构造一个string类对象
	cout << s2 << endl;

	string s3(s2);	// 拷贝构造
	cout << s3 << endl;

	string s4(s3, 6, 5);  // 拷贝构造的重载 从下标6位置开始拷贝 拷贝5个字符
	cout << s4 << endl;

	string s5("hello" , 3); // 拷贝 `hello` 前3个字符
	cout << s5 << endl;

	string s6(10 , 'a'); // 使用 10个 `a` 填充对象
	cout << s6 << endl;

	string s7(s6.begin() , s6.end()); // 迭代器序列初始化
	cout << s7 << endl;


	return 0;
}

output:

在这里插入图片描述


ps: npos 原型:static const size_t npos = -1;npos 的访问:string::npos。无符号的 -1 相当于是整型的最大值,若当不传这个参数时, 或者 len 大于后面剩余字符的长度,那么使用默认参数 npos都是相当于 直到字符串的结束。[ 返回 ]

在这里插入图片描述


🌟 std::string::operator= 赋值重载

序号函数名称功能
1️⃣string& operator= (const string& str)用一个新的 string 对象替换当前 string 对象的内容
2️⃣string& operator= (const char * s)用一个c的字符串替换当前 string 对象内容
3️⃣string& operator= (char c)使用一个字符替换当前 string 对象的内容
#include <iostream>
#include <string>
using namespace std;

int main() {

	string s1 = "hello world";
// 1.
	string temp = "ccc";
	s1 = temp;
	cout << s1 << endl;
// 2.
	s1 = "hhhh";
	cout << s1 << endl;
// 3.
	s1 = 'a';
	cout << s1 << endl;

	return 0;
}

output:

在这里插入图片描述


🌟 元素的访问

序号函数名称功能
1️⃣char& operator[] (size_t pos)返回当前 string 对象中 pos 位置字符的引用
2️⃣const char& operator[](size_t pos) const返回当前 const string 对象中 pos 位置字符的引用
3️⃣char& at (size_t pos)返回当前 string 对象中 pos 位置字符的引用
4️⃣const char& at (size_t pos) const返回当前 const string 对象中 pos 位置字符的引用
5️⃣char& back()返回当前 string 对象最后一个字符的引用
6️⃣const char& back() const返回当前 const string 对象最后一个字符的引用
7️⃣char& front()返回当前 string 对象第一个字符的引用
8️⃣const char& front() const返回当前 const string 对象第一个字符的引用

ps: at[] 的行为是一样的,函数都会检查 pos 是否是合法位置,若不是,[] 是断言错误,而 at 是抛异常。

ps: back == [xx.size() - 1]front == [0]

#include <iostream>
#include <string>
using namespace std;

int main() {

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

	cout << endl;

	string s2 = "world";
	for (size_t i = 0; i < s2.size(); i++) {
		s2[i]++;
		cout << s2[i] << " ";
	}

	cout << endl;

	string s3 = "hello world";
	cout << s3.back() << s3[s3.size() - 1] << endl;
	cout << s3.front() << s3[0] << endl;
	cout << s3.at(4) << endl;

	return 0;
}

output:

在这里插入图片描述


🌟 元素的长度

序号函数名称功能
1️⃣size_t size() const返回 string 对象实际字符的长度
2️⃣size_t length() const返回 string 对象实际字符的长度
#include <iostream>
#include <string>
using namespace std;

int main() {

	string s = "hello world";
	cout << s.size() << endl;	// 11
	cout << s.length() << endl;	// 11

	return 0;
}

🌟 string 迭代器

序号函数名称功能
1️⃣iterator begin()返回一个迭代器,该迭代器指向 string 对象的第一个字符
2️⃣const_iterator begin() const返回一个迭代器,该迭代器指向 const string 对象的第一个字符
3️⃣iterator end()返回一个迭代器,该迭代器指向 string 对象最后一个实际字符的下一个位置
4️⃣const_iterator end() const返回一个迭代器,该迭代器指向 const string 对象最后一个实际字符的下一个位置
5️⃣reverse_iterator rbegin()返回一个反向迭代器,该迭代器指向 string 对象最后一个实际字符的位置
6️⃣const_reverse_iterator rbegin() const返回一个反向迭代器,该迭代器指向 const string 对象最后一个实际字符的位置
7️⃣reverse_iterator() rend()返回一个反向迭代器,该迭代器指向 string 对象第一个字符的前一个位置
8️⃣const_reverse_iterator() rend() const返回一个反向迭代器,该迭代器指向 const string 对象第一个字符的前一个位置

ps: [ begin() , end() )( rend() , rbegin() ]

#include <iostream>
#include <string>
using namespace std;

int main() {

	string s = "hello world";
	for (string::iterator it = s.begin(); it != s.end(); it++) {
		cout << *it << " ";
	}
	// output: h e l l o   w o r l d
	cout << endl;

	// 自动迭代 自动判断结束
	// 范围for 本质上调用的也是迭代器
	for (auto val : s) {
		cout << val << " ";
	}
	// output: h e l l o   w o r l d
	cout << endl;

	for (string::reverse_iterator it = s.rbegin(); it != s.rend(); it++) {
		cout << *it << " ";
	}
	// output: d l r o w   o l l e h
	cout << endl;

	// const 
	const string s2 = "nihao";
	string::const_iterator it = s2.begin();
	while (it != s2.end()) {
		cout << *it << " ";
		it++;
	}
	// output: n i h a o

	cout << endl;
	string::const_reverse_iterator rit = s2.rbegin();
	while (rit != s2.rend()) {
		cout << *rit << " ";
		rit++;
	}
	// output: o a h i n

	return 0;
}

output:

在这里插入图片描述


🌟 string 对象修改

序号函数名称功能
1️⃣void push_back (char c)在当前 string 对象的末尾追加一个 c 字符
2️⃣string& append (const string& str)在当前 string 对象的末尾追加一个 const string str 对象
3️⃣string& append (const string& str , size_t subpos , size_t sublen)在当前 string 对象的末尾追加一个 const string str 对象的子串,从 subpos 位置开始,拷贝 sublen 个字符过去
类似上面构造函数的 npos 用法
4️⃣string& append (const char* s);在当前 string 对象的末尾追加一个 c_string 字符串
5️⃣template <class InputIterator> string& append (InputIterator first , InputIterator last) 追加一个迭代器序列的字符串 [first , last)
#include <iostream>
#include <string>
using namespace std;

int main() {

	string s = "hello";
	s.push_back('-');
	cout << s << endl;

	s = "hello";
	string temp = " world";
	s.append(temp);
	cout << s << endl;

	string s2 = "hello";
	string temp2 = " world";
	s2.append(temp2 , 0 , 3);
	cout << s2 << endl;

	string s3 = "hello";
	s3.append(" world");
	cout << s3 << endl;

	string s4 = "hello";
	s4.append(s4.begin(), s4.end());
	cout << s4 << endl;

	string s5 = "hello";
	s5.append(s5.rbegin() , s5.rend());
	cout << s5 << endl;

	return 0;
}

output:

在这里插入图片描述


std::string::operator+= 运算符重载

序号函数名称功能
6️⃣string& operator+= (const string& str);在当前 string 对象的末尾追加一个 const string str 对象
7️⃣string& operator+= (const char* s);在当前 string 对象的末尾追加一个 c_string 字符串
8️⃣string& operator+= (char c);在当前 string 对象的末尾追加一个 c 字符
#include <iostream>
#include <string>
using namespace std;

int main() {

	string s = "he";
	s += 'l';
	s += 'l';
	s += "o ";
	string temp = "world";
	s += temp;
	cout << s << endl;
	
	// output: hello world

	return 0;
}

🌟 元素的容量

序号函数名称功能
1️⃣size_t capacity() const返回当前 string 对象的容量大小
2️⃣void reserve (size_t n = 0)改变当前 string 对象的容量为 n
3️⃣void resize (size_t n)将当前 string 对象的 size() 调整为 n 并初始化为 '\0'
4️⃣void resize (size_t n , char c)将当前 string 对象的 size() 调整为 n 并初始化为 c
5️⃣void clear();删除当前 string 对象的所有内容,size() = 0
6️⃣bool empty() const若当前 string 对象为空返回 true,否则返回 false

ps: reserve 是改变容量,而 resize 是改变 size() + 初始化,resizen 传的比 string 的大小还小,则就是删除。

#include <iostream>
#include <string>
using namespace std;

int main() {

	string s = "hello";
	cout << s.capacity() << endl;
	s.reserve(100);
	cout << s.capacity() << endl;
	cout << s.size() << endl; // 5
	
	string s2 = "hello world";
	s2.resize(5);
	cout << s2.size() << endl;	// 100
	cout << s2 << endl;
	s2.clear();
	cout << s2.empty() << endl;


	return 0;
}

output:

在这里插入图片描述


🌟 std::string::insert 插入

在这里插入图片描述


ps: 需要的查文档即可,效率不高很少用。

🌟 std::string::erase 删除

在这里插入图片描述


🌟 std::string::c_str 返回c的字符串

序号函数名称功能
1️⃣const char* c_str() const返回c的字符串使用 '\0' 结尾

🌟 查找

序号函数名称功能
1️⃣size_t find (char c , size_t pos = 0) const从当前 string 对象的 pos 位置开始查找 c 字符,返回这个字符第一次出现的位置,否则返回 string::npos
2️⃣string substr (size_t pos = 0 , size_t len = npos) const返回当前对象 pos 位置开始的 len 个字符的子串
#include <iostream>
#include <string>
using namespace std;

int main() {

	string s = "hello world";
	size_t res = s.find('w' , 0);
	if (res != string::npos) {
		cout << s.substr(res) << endl;	// world
	}

	return 0;
}
序号函数名称功能
3️⃣size_t rfind (char c , size_t pos = npos) const从当前 string 对象的 pos 位置从后向前开始查找 c 字符,返回这个字符最后一次出现的位置,否则返回 string::npos

🌟 其他

序号函数名称功能
1️⃣istream& getline (istream& is , string& str , char delim)输入一行字符遇到 delim 终止
2️⃣istream& getline (istream& is , string& str)输入一行字符遇到 \n 终止
3️⃣string to_string (int val)返回一个 valstring 对象
4️⃣int stoi (const string& str, size_t* idx = 0, int base = 10)字符串转整数。 idx 通常都为 nullptrbase 代表进制

ps: to_string 支持的转换类型

在这里插入图片描述


ps: string 可以转换为的类型

在这里插入图片描述


#include <iostream>
#include <string>
using namespace std;

int main() {

	int val = 10;
	string s_val = to_string(val);
	cout << s_val << endl;	 // 10
	

	val = stoi(s_val);
	cout << val << endl;	// 10

	return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/81420.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

4 STM32标准库函数 之 FLASH存储器(FLASH)所有函数的介绍及使用

3 STM32标准库函数 之 FLASH存储器所有函数的介绍及使用 1. 图片有格式2 文字无格式二、FLASH 库函数固件库函数预览2.1 函数FLASH_SetLatency2.2 函数FLASH_HalfCycleAccessCmd2.3 函数FLASH_PrefetchBufferCmd2.4 函数FLASH_Unlock2.5 函数FLASH_Lock2.6 函数FLASH_ErasePage…

音视频 FFmpeg音视频处理流程

ffmpeg -i test_1920x1080.mp4 -acodec copy -vcodec libx264 -s 1280x720 test_1280x720.flv推荐一个零声学院项目课&#xff0c;个人觉得老师讲得不错&#xff0c;分享给大家&#xff1a; 零声白金学习卡&#xff08;含基础架构/高性能存储/golang云原生/音视频/Linux内核&am…

GAN!生成对抗网络GAN全维度介绍与实战

目录 一、引言1.1 生成对抗网络简介1.2 应用领域概览1.3 GAN的重要性 二、理论基础2.1 生成对抗网络的工作原理2.1.1 生成器生成过程 2.1.2 判别器判别过程 2.1.3 训练过程训练代码示例 2.1.4 平衡与收敛 2.2 数学背景2.2.1 损失函数生成器损失判别器损失 2.2.2 优化方法优化代…

Linux设置临时目录路径的解决方案

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。喜欢通过博客创作的方式对所学的…

第 7 章 排序算法(1)(介绍,分类,时间复杂度,空间复杂度)

7.1排序算法的介绍 排序也称排序算法(Sort Algorithm)&#xff0c;排序是将一组数据&#xff0c;依指定的顺序进行排列的过程。 7.2排序的分类&#xff1a; 内部排序: 指将需要处理的所有数据都加载到**内部存储器(内存)**中进行排序。外部排序法&#xff1a; 数据量过大&am…

安全学习DAY18_信息打点-APP资产搜集

信息打点-APP资产&静态提取&动态抓包&动态调试 文章目录 信息打点-APP资产&静态提取&动态抓包&动态调试本节知识&思维导图本节使用到的链接&工具 如何获取目标APP从名称中获取APP从URL获取APP APP搜集资产信息APP提取信息分类信息提取方式信息…

RPA机器人《国网电力》电力行业实施案例-基层减负 提质增效

背景&#xff1a;随着国网战略目标加速落地&#xff0c;数字化转型和精益化管理深化推进&#xff0c;各供电公司亟待突破精细化管控不深入、执行标准不够统一、系统数据不够融通等制约工作质效提升的能力瓶颈&#xff0c;针对这些问题&#xff0c;决定引入诸如RPA、OCR等技术&a…

深入探索:Kali Linux 网络安全之旅

目录 前言 访问官方网站 导航到下载页面 启动后界面操作 前言 "Kali" 可能指的是 Kali Linux&#xff0c;它是一种基于 Debian 的 Linux 发行版&#xff0c;专门用于渗透测试、网络安全评估、数字取证和相关的安全任务。Kali Linux 旨在提供一系列用于测试网络和…

C语言刷题指南(二)

&#x1f4d9;作者简介&#xff1a; 清水加冰&#xff0c;目前大二在读&#xff0c;正在学习C/C、Python、操作系统、数据库等。 &#x1f4d8;相关专栏&#xff1a;C语言初阶、C语言进阶、C语言刷题训练营、数据结构刷题训练营、有感兴趣的可以看一看。 欢迎点赞 &#x1f44d…

回归预测 | MATLAB实现WOA-BP鲸鱼优化算法优化BP神经网络多输入单输出回归预测(多指标,多图)

回归预测 | MATLAB实现WOA-BP鲸鱼优化算法优化BP神经网络多输入单输出回归预测&#xff08;多指标&#xff0c;多图&#xff09; 目录 回归预测 | MATLAB实现WOA-BP鲸鱼优化算法优化BP神经网络多输入单输出回归预测&#xff08;多指标&#xff0c;多图&#xff09;效果一览基本…

Linux 内存管理 pt.1

今天我们来学习一下 Linux 操作系统核心之一&#xff1a;内存 跟 CPU 一样&#xff0c;内存也是操作系统最核心的功能之一&#xff0c;内存主要用来存储系统和程序的指令、数据、缓存等 关于内存的学习&#xff0c;我会尽量以通俗易懂的方式且分成多篇文章去讲解 那么今天在 pt…

史上最简洁实用人工神经元网络c++编写202301

这是史上最简单、清晰…… C语言编写的 带正向传播、反向传播(Forward ……和Back Propagation&#xff09;……任意Nodes数的人工神经元神经网络……。 大一学生、甚至中学生可以读懂。 适合于&#xff0c;没学过高数的程序员……照猫画虎编写人工智能、深度学习之神经网络……

学习笔记230816---vue项目中使用第三方组件{el-dropdown}如何设置禁止事件功能

问题描述 使用第三方组件elementui&#xff0c;在导航菜单el-menu的el-menu-item中嵌入一个下拉菜框el-dropdown。点击...icon弹出下拉菜单el-dropdown-menu&#xff0c;那么这时会触发事件冒泡&#xff0c;el-menu-item菜单项的点击事件也会触发。 解决方法 阻止事件冒泡&am…

Pycharm找不到Conda可执行文件路径(Pycharm无法导入Anaconda已有环境)

在使用Pycharm时发现无法导入Anaconda创建好的环境&#xff0c;会出现找不到Conda可执行文件路径的问题。 解决 在输入框内输入D:\anaconda3\Scripts\conda.exe&#xff0c;点击加载环境。 注意前面目录是自己Anaconda的安装位置&#xff0c;之后就可以找到Anaconda的现有环…

C++ 的关键字(保留字)完整介绍

1. asm asm (指令字符串)&#xff1a;允许在 C 程序中嵌入汇编代码。 2. auto auto&#xff08;自动&#xff0c;automatic&#xff09;是存储类型标识符&#xff0c;表明变量"自动"具有本地范围&#xff0c;块范围的变量声明&#xff08;如for循环体内的变量声明…

腾讯云3年轻量应用服务器2核4G5M和2核2G4M详细介绍

腾讯云轻量应用服务器3年配置&#xff0c;目前可以选择三年的轻量配置为2核2G4M和2核4G5M&#xff0c;2核2G4M和2核4G5M带宽&#xff0c;当然也可以选择选一年&#xff0c;第二年xufei会比较gui&#xff0c;腾讯云百科分享腾讯云轻量应用服务器3年配置表&#xff1a; 目录 腾…

【C# 基础精讲】异步和同步的区别

异步&#xff08;Asynchronous&#xff09;和同步&#xff08;Synchronous&#xff09;是在编程中经常遇到的两种执行模式。它们涉及到程序中任务的执行方式以及对资源的管理方式。在本文中&#xff0c;我们将深入探讨异步和同步的区别、使用场景以及在 C# 中如何实现异步编程。…

AutoHotKey+VSCode开发扩展推荐

原来一直用的大众推荐的SciTeAHK版&#xff0c;最近发现VSCode更舒服一些&#xff0c;有几个必装的扩展推荐一下&#xff1a; AutoHotkey Plus 请注意不是AutoHotkey Plus Plus。如果在扩展商店里搜索会有两个&#xff0c;一个是Plus&#xff0c;一个是Plus Plus。我选择Pllus&…

【Git】分支管理

文章目录 一、理解分支二、创建、切换、合并分支三、删除分支四、合并冲突五、合并模式六、分支策略七、bug分支八、强制删除分支 努力经营当下 直至未来明朗&#xff01; 一、理解分支 HEAD指向的是master分支&#xff0c;master中指向的是最新一次的提交&#xff0c;也就是m…

Python数据分析实战-多线程并发处理列表(附源码和实现效果)

实现功能 Python数据分析实战-多线程并发处理列表 实现代码 import threading有15个列表&#xff0c;尝试多进程并发处理&#xff0c;每个列表一个进程&#xff0c;进程数和 CPU 核数一致def sum_list(lst):return sum(lst)if __name__ __main__:lists [[1,2,3], [4,5,6], …
最新文章