string 的介绍及使用

news2024/9/25 2:17:47

一.string类介绍

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

        C++中将string封装为单独的类,string 类是 C++ 标准库中的一个非常重要的类,用于表示和操作字符串。string类位于命名空间std(标准库)下,使用string类记得加上头文件#include,并且使用命名空间using namespace std或者using std::string。注意:string低层还是模版。

二.string类的常用接口

1.构造函数(constructor)

1、无参构造:string(); 构造空的string类对象,即空字符串。常用。

2、有参构造:string (const char* s); 用常量字符串来构造string类对象常用。

3、拷贝构造:string (const string& str); 用str拷贝构造string类对象常用。
4、string (const string& str, size_t pos, size_t len = npos); 构造从下标pos开始,长度为len的子串,含缺省参数npos。
5、string (const char* s, size_t n); 构造前n个字符组成的子串。
6、string (size_t n, char c); 构造n个字符c组成的字符串。

int main()
{
	string s1;
	string s2("hello xzy");
	string s3(s2);
	string s4(s2, 6, 3);
	string s5("hello xzy", 5);
	string s6(10, 'x');

	cout << s1 << endl;//输出:
	cout << s2 << endl;//输出:hello xzy
	cout << s3 << endl;//输出:hello xzy
	cout << s4 << endl;//输出:xzy
	cout << s5 << endl;//输出:hello
	cout << s6 << endl;//输出:xxxxxxxxxx

	return 0;
}

2、析构函数(destructor)

~string(); 程序结束前自动调用,释放堆区动态开辟的资源

3.运算符重载(operator )

1.operator=

  1. string& operator= (const string& str); 常用。
  2. string& operator= (const char* s);
  3. string& operator= (char c);
int main()
{
	string s1;
	string s2;
	string s3;

	//赋值重载
	s1 = "hello xzy";
	s2 = s1;
	s3 = 'v';

	//拷贝构造
	string s4 = s1;

	cout << s1 << endl;//输出:hello xzy
	cout << s2 << endl;//输出:hello xzy
	cout << s3 << endl;//输出:v
	cout << s4 << endl;//输出:hello xzy

	return 0;
}

2.operator[ ]

int main()
{
	string s1("hello xzy");
	s1[6] = 'w';
	s1[7] = 'j';
	s1[8] = '\0';
	cout << s1 << endl; //输出:hello wj

	s1[10] = 'A'; //下标越界,内部断言assert报错
	
	return 0;
}

3.operator+=

  1. string& operator+= (const string& str); 常用。
  2. string& operator+= (const char* s);
  3. string& operator+= (char c);
int main()
{
	string s1("hello xzy");
	string s2(" how are you");
	s1 += s2;
	cout << s1 << endl;

	s1 += "???";
	cout << s1 << endl;

	s1 += '!';
	cout << s1 << endl;

	return 0;
}

4.operator+

  1. string operator+ (const string& lhs, const string& rhs);
  2. string operator+ (const string& lhs, const char* rhs);
  3. string operator+ (const char* lhs, const string& rhs);
int main()
{
	string s1("hello");
	string s2 = s1 + " world";
	string s3 = "xzy " + s1;
	string s4 = s2 + s3;
	cout << s2 << endl; //hello world
	cout << s3 << endl; //xzy hello
	cout << s4 << endl; //hello worldxzy hello

	return 0;
}

 4、string的四种迭代器(iterator)

        迭代器是一种用于遍历容器元素的对象(并非类,而是设计模式中的一种行为模式),它提供了一种通用的访问容器元素的方式,无论容器的类型和数据结构如何。迭代器在C++标准库中被广泛使用,特别是在处理如vector、list、map等容器时。

1.正向迭代器 iterator

返回正向迭代器:可以修改字符串。

1、iterator begin(); 返回字符串的第一个字符。

2、iterator end(); 返回字符串最后一个有效字符(不含\0)的下一个字符。



int main()
{
	string s1("hello ryc");
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	return 0;
}

 2.反向迭代器 reverse_iterator

返回反向迭代器:可以修改字符串。

reverse_iterator rbegin(); 返回字符串最后一个有效字符(不含\0)。

reverse_iterator rend(); 返回字符串第一个字符的前一个字符。


int main()
{
	string s1("hello ryc");
	string::reverse_iterator rit = s1.rbegin();
	while (rit != s1.rend())
	{
		cout << *rit << " ";
		rit++;
	}
	cout << endl;

	return 0;
}

3.const修饰的正向迭代器 const_iterator

返回const修饰的正向迭代器:不可以修改字符串。

  1. const_iterator begin() const;
  2. const_iterator end() const;

 4.const修饰的反向迭代器 const_reverse_iterator

返回const修饰的反向迭代器:不可以修改字符串。

  1. const_reverse_iterator rbegin() const;
  2. const_reverse_iterator rend() const;

 5.string类对象的容量操作

  1. size_t size() const; 返回字符串有效字符长度(不包括\0)。常用。
  2. size_t length() const; 返回字符串有效字符长度(不包括\0)。
  3. size_t capacity() const; 返回空间总大小(不包括\0)。常用。
  4. void resize (size_t n); 为字符串预留大于等于n的空间(不包括\0),避免扩容,提高效率。常用。
  5. void clear(); 清空数据,但是一般不清容量。常用。
  6. bool empty() const; 判断是否为空。常用。

注意:

  1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
  2. clear()只是将string中有效字符清空,不改变底层空间大小。

6.string类对象的修改操作

  1. void push_back (char c); 在字符串后尾插字符c。
  2. void pop_back(); 在字符串尾删一个字符。
  3. string& append (const string& str); 在字符串后追加一个字符串。
  4. string& assign (const string& str, size_t subpos, size_t sublen); 拷贝字符串:从下标为subpos开始,拷贝长度为sublen的字符串到string类对象里面。
  5. string& insert (size_t pos, const string& str); 在pos位置处插入字符串到string类对象里面。(由于效率问题(移动数据),谨慎使用)。
  6. string& erase (size_t pos = 0, size_t len = npos); 从pos位置开始删除长度为npos个字符。(由于效率问题(移动数据),谨慎使用)。
  7. void swap (string& str); 交换字符串。
  8. string& replace (size_t pos, size_t len, const string& str); 从pos位置开始的长度为len的子串,替换为str。(伴随着插入与删除,效率低,谨慎使用)。
int main()
{
	string s1("hello ryc");
	s1.push_back('!');
	cout << s1 << endl;
	s1.pop_back();
	cout << s1 << endl;
	s1.append("666");
	cout << s1 << endl;

	//可以使用+=代替尾差
	s1 += "maldsk";
	cout << s1 << endl;

	s1.insert(0, "why");
	cout << s1 << endl;

	string s2("why did you do so? I don't know!");
	s2.erase(0, 1);
	cout << s2 << endl;


	s2.replace(0,2,"adw2y");
	cout << s2 << endl;

	string s5("hello x hello x");
	string tmp;
	tmp.reserve(s5.size());
	for (auto ch : s5)
	{
		if (ch == 'x')
		{
			tmp += "xy";
		}
		else
		{
			tmp += ch;
		}
	}
	cout << tmp << endl;
	
	swap(tmp, s5);
	cout << s5 << endl;

	return 0;
}

9、const char* c_str() const; 返回C格式字符串。方便调用C中的接口。

7.string类对象的查找操作

  1. string substr (size_t pos = 0, size_t len = npos) const; 找子串:返回从pos位置开始,长度为npos的string类。
  2. size_t find (char c, size_t pos = 0) const; 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置。
  3. size_t rfind (char c, size_t pos = npos) const; 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置。找不到返回-1。
  4. size_t find_first_of (const char* s, size_t pos = 0) const; 从字符串pos位置开始从前往后找字符串s中出现的字符,返回该字符在字符串中的位置。
  5. size_t find_last_of (const char* s, size_t pos = npos) const; 从字符串pos位置开始从后往前找字符串s中出现的字符,返回该字符在字符串中的位置。
  6. size_t find_first_not_of (const char* s, size_t pos = 0) const; 从字符串pos位置开始从前往后找字符串s中没有出现的字符,返回该字符在字符串中的位置。
  7. size_t find_last_not_of (const char* s, size_t pos = npos) const; 从字符串pos位置开始从后往前找字符串s中没有出现的字符,返回该字符在字符串中的位置。
int main()
{
	//suffix:后缀

	string s1("test.cpp");
	size_t pos1 = s1.find(".");
	string suffix1 = s1.substr(pos1);
	cout << suffix1 << endl; //.cpp

	string s2("test.cpp.zip");
	size_t pos2 = s2.rfind(".");
	string suffix2 = s2.substr(pos2);
	cout << suffix2 << endl; //.zip

	string s3("hello ryc");
	size_t found = s3.find_first_of("ryc");
	while (found != string::npos)
	{
		s3[found] = '*';
		found = s3.find_first_of("ryc", found + 1);
	}
	cout << s3 << endl; //hello ***

	string str1("/user/bin/man");
	cout << endl << str1 << "的路径名与文件名如下:" << endl;
	size_t found1 = str1.find_last_of("/\\");
	cout << "path:" << str1.substr(0, found1) << endl;
	cout << "file:" << str1.substr(found1 + 1) << endl;

	string str2("c:\\windows\\winhelp.exe");
	cout << endl << str2 << "的路径名与文件名如下:" << endl;
	size_t found2 = str2.find_last_of("/\\");
	cout << "path:" << str2.substr(0, found2) << endl;
	cout << "file:" << str2.substr(found2 + 1) << endl;

	return 0;
}

8.string类对象的遍历操作

1.下标 + []


int main()
{
	string s1("hello ryc");

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

	cout << endl << s1 << endl;


	return 0;
}

2.迭代器

int main()
{
	string s1("hello ryc");
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		*it += 2;//可以修改
		cout << *it << " ";
		++it;
	}
	cout << endl << s1 << endl;

	return 0;
}

3.auto和范围for

int main()
{
	string s1("hello ryc");
	//范围for 自动迭代 自动判断结束
	//底层就是迭代器
	for (auto ch : s1)
	{
		ch += 2;//修改ch对s1无影响,ch是它的拷贝
		cout << ch << " ";
	}
	cout << endl << s1 << endl;

	return 0;
}
int main()
{
	string s1("hello ryc");
	//范围for 自动迭代 自动判断结束
	//底层就是迭代器
	for (auto& ch : s1)
	{
		ch += 2;//修改ch对s1无影响,ch是它的拷贝
		//加上引用即可!
		cout << ch << " ";
	}
	cout << endl << s1 << endl;

	return 0;
}

1.auto关键字

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

2.范围for

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

	for (auto i : array)
	{
		cout << i << " ";
	}
	cout << endl;

	return 0;
}

三、非成员函数:getline()

istream& getline (istream& is, string& str, char delim); delim:分隔符
istream& getline (istream& is, string& str);

类似C语言中的scanf(“%s”, str),但是其遇到空格会停止;
C++中引入了getline优化了scanf遇到的问题,默认遇到\n才停止,也可以自定义停止字符delim。

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

int main() 
{
    string str;
    getline(cin, str);
    size_t pos = str.rfind(' ');
    string sub = str.substr(pos + 1);
    cout << sub.size() << endl;
}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

BUUCTF [SCTF2019]电单车详解两种方法(python实现绝对原创)

使用audacity打开&#xff0c;发现是一段PT2242 信号 PT2242信号 有长有短&#xff0c;短的为0&#xff0c;长的为1化出来 这应该是截获电动车钥匙发射出的锁车信号 0 01110100101010100110 0010 0前四位为同步码0 。。。中间这20位为01110100101010100110为地址码0010为功…

ssm病人跟踪治疗信息管理系统

专业团队&#xff0c;咨询就送开题报告&#xff0c;欢迎大家咨询留言 摘 要 病人跟踪治疗信息管理系统采用B/S模式&#xff0c;促进了病人跟踪治疗信息管理系统的安全、快捷、高效的发展。传统的管理模式还处于手工处理阶段&#xff0c;管理效率极低&#xff0c;随着病人的不断…

《SG-Former: Self-guided Transformer with Evolving Token Reallocation》ICCV2023

摘要 SG-Former&#xff08;Self-guided Transformer&#xff09;是一种新型的视觉Transformer模型&#xff0c;旨在解决传统Transformer在处理大型特征图时面临的计算成本高的问题。该模型通过一种自适应细粒度的全局自注意力机制&#xff0c;实现了有效的计算成本降低。它利…

VmWare安装虚拟机教程(centos7)

VMWare下载&#xff1a; 下载 VMware Workstation Pro - VMware Customer Connect 安装包&#xff1a;&#xff08;16的版本&#xff09;免费&#xff01;&#xff08;一个赞就行&#xff09; 一直点下一步即可&#xff0c;注意修改一下安装位置就好 二、安装虚拟机 安装虚…

鸭脖变“刺客”,啃不起了

撰文&#xff5c;ANGELICA 编辑&#xff5c;ANGELICA 审核&#xff5c;烨 Lydia 声明&#xff5c;图片来源网络。日晞研究所原创文章&#xff0c;如需转载请留言申请开白。 你有多久没吃卤味了&#xff1f; 2020年之后&#xff0c;人们对于几大卤味巨头的关注度正在下降。 …

视频字幕生成:分享6款专业易操作的工具,让创作更简单!

​视频字幕如何添加&#xff1f;日常剪辑Vlog视频时&#xff0c;就需要给视频添加上字幕了。字幕是一个比较重要的元素&#xff0c;它不仅可以帮助听力受损或语言障碍的人士理解内容&#xff0c;还可以让你的视频更加易于理解和吸引观众。 那么如何实现视频字幕生成&#xff0c…

【LLaMa2入门】从零开始训练LLaMa2

目录 1 背景2 搭建环境2.1 硬件配置2.2 搭建虚拟环境2.2.1 创建虚拟环境2.2.2 安装所需的库 3 准备工作3.1 下载GitHub代码3.2 下载模型3.3 数据处理3.3.1 下载数据3.3.2 数据集tokenize预处理 4 训练4.1 修改配置4.2 开始训练4.3 多机多卡训练 5 模型推理5.1 编译5.1.1 安装gc…

ResNet18模型扑克牌图片预测

加入会员社群&#xff0c;免费获取本项目数据集和代码&#xff1a;点击进入>> 1. 项目简介 该项目旨在通过深度学习技术&#xff0c;使用ResNet18模型对扑克牌图像进行预测与分类。扑克牌图片分类任务属于图像识别中的一个应用场景&#xff0c;要求模型能够准确识别扑克…

【python篇】python pickle模块一篇就能明白,快速理解

持久性就是指保持对象&#xff0c;甚至在多次执行同一程序之间也保持对象。通过本文&#xff0c;您会对 Python对象的各种持久性机制&#xff08;从关系数据库到 Python 的 pickle以及其它机制&#xff09;有一个总体认识。另外&#xff0c;还会让您更深一步地了解Python 的对象…

音视频入门基础:FLV专题(5)——FFmpeg源码中,判断某文件是否为FLV文件的实现

一、引言 通过FFmpeg命令&#xff1a; ./ffmpeg -i XXX.flv 可以判断出某个文件是否为FLV文件&#xff1a; 所以FFmpeg是怎样判断出某个文件是否为FLV文件呢&#xff1f;它内部其实是通过flv_probe函数来判断的。从《FFmpeg源码&#xff1a;av_probe_input_format3函数和AVI…

Serilog文档翻译系列(五) - 编写日志事件

日志事件通过 Log 静态类或 ILogger 接口上的方法写入接收器。下面的示例将使用 Log 以便语法简洁&#xff0c;但下面显示的方法同样可用于接口。 Log.Warning("Disk quota {Quota} MB exceeded by {User}", quota, user); 通过此日志方法创建的警告事件将具有两个相…

mes系统在中小企业智能制造作用

MES系统&#xff08;制造执行系统&#xff09;在中小企业智能制造中扮演着至关重要的角色&#xff0c;其作用主要体现在以下几个方面&#xff1a; 1. 提升生产效率与质量 实时监控与数据采集&#xff1a;MES系统能够实时采集生产现场的各项数据&#xff0c;如设备状态、生产进…

nmap 命令:网络扫描

一、命令简介 ​nmap​&#xff08;Network Mapper&#xff09;是一个开放源代码的网络探测和安全审核的工具。它最初由Fyodor Vaskovich开发&#xff0c;用于快速地扫描大型网络&#xff0c;尽管它同样适用于单个主机。 ​nmap​的功能包括&#xff1a; 发现主机上的开放端…

电信、移动、联调等运营商都有那些国产化自研软件

国产化自研软件方面有着积极的探索和实践&#xff0c;包括操作系统、数据库和中间件等&#xff0c;电信运营商在国产化软件方面取得了显著进展&#xff1a; 操作系统&#xff1a; 中国电信推出了基于华为欧拉openEuler开源系统的天翼云操作系统CTyunOS&#xff0c;已上线部署5万…

【2024W38】肖恩技术周刊(第 16 期):白嫖AI的最佳时段

周刊内容: 对一周内阅读的资讯或技术内容精品&#xff08;个人向&#xff09;进行总结&#xff0c;分类大致包含“业界资讯”、“技术博客”、“开源项目”和“工具分享”等。为减少阅读负担提高记忆留存率&#xff0c;每类下内容数一般不超过3条。 更新时间: 星期天 历史收录:…

asp.net core日志与异常处理小结

asp.net core的webApplicationBuilder中自带了一个日志组件,无需手动注册服务就能直接在控制器中构造注入&#xff0c;本文主要介绍了net core日志与异常处理小结&#xff0c;需要的朋友可以参考下 ILogger简单使用 asp.net core的webApplicationBuilder中自带了一个日志组件…

Elasticsearch可视化工具ElasticHD

目录 介绍 ElasticHD应用程序页面 安装 基本用法 独立可执行文件 ES版本支持 SQL特性支持: 超越SQL功能支持: SQL的用法 Docker快速入门: 下载地址 介绍 ElasticHD是ElasticSearch可视化管理工具。它不需要任何软件。它在您的Web浏览器中工作,允许您随时随地管理…

unshare -p时提示Cannot allocate memory如何解决

当使用unshare -p命令时&#xff0c;出现如下报错&#xff1a; unshare -p /bin/bash bash: fork: Cannot allocate memory 如果想要正常使用&#xff0c;只需要添加–fork选项就行 unshare -p --fork /bin/bash 在使用 unshare -p 创建新的 PID 命名空间时&#xff0c;存在一…

aws s3 存储桶 前端组件上传简单案例

写一个vue3 上传aws oss存储的案例 使用到的插件 npm install aws-sdk/client-s3 注意事项 &#xff1a; 1. 本地调试 &#xff0c; 需要设置在官网设置跨域 必须&#xff01;&#xff01;&#xff01; 否则调试不了 &#xff0c;前端代理是不起作用的 &#xff0c;因为是插…

如何通过蜂巢(容器安全)管理内部部署数据安全产品与云数据安全产品?

本文将探讨内部部署和云数据安全产品之间的主要区别。在思考这个问题之前&#xff0c;首先了解内部部署和云数据安全产品之间的主要区别。 内部部署数据安全产品意味着管理控制台位于企业客户的内部部署&#xff0c;而德迅云安全则在云中托管云数据安全产品。德迅云安全供应商通…