C++string(二)

news2025/2/25 6:01:44

我们上次讲完了Element access,现在我们继续往下讲:

一.Modifiers:

1.operator+=:

Extends the string by appending additional characters at the end of its current value:
翻译:在string类对象结尾追加字符

如下:

#include <string>
int main()
{
    //使用场景:
    string s1 = "hello ";
    //1.追加字符  string& operator+= (char c)
    s1 += 'w';
    cout <<"string& operator+= (char c):"<<s1 << endl;
    //2.追加字符串   string& operator+= (const char* s)
    s1 += "orld";
    cout << "string& operator+= (const char* s):" << s1 << endl;
    //3.追加string   string& operator+= (const string& str)
    string s2 = " good man";
    s1 += s2;
    cout << "string& operator+= (const string& str):" << s1 << endl;
    return 0;
}

2.append:

Extends the string by appending additional characters at the end of its current value:

翻译:延伸string对象通过在其对象结尾追加字符(串)追加

#include <string>
int main()
{
    //常用情景:
    string s1("hello world");//==string s1="hello world"
    //string& append (size_t n, char c);
    //注意:append无:string& append (char c);
    s1.append(1, '!');
    cout << s1 << endl;
    //string& append (const char* s);
    s1.append("hello bit");
    cout << s1 << endl;
    //string& append (const string& str);
    string s2("  apple ");
    s1.append(s2);
    cout << s1 << endl;
    //string& append (InputIterator first, InputIterator last);
    s1.append(++s2.begin(), --s2.end());//注意:改变apple间距了
    cout << s1 << endl;
    return 0;
}

3.push_back:

Appends character c to the end of the string, increasing its length by one.

翻译:在string对象结尾追加单个字符,从而增长其长度

该函数补充了append无:string& append (char c)的缺陷

4.assign:

Assigns a new value to the string, replacing its current contents.

翻译:将新的内容替换其之前的内容

接口和append几乎相同,所以这里不做讲解

5.insert:

Inserts additional characters into the string right before the character indicated by pos (or p):

翻译:在pos位置前插入字符串

#include <string>
int main()
{
    string str = "to be question";
    string str2 = "the ";
    string str3 = "or not to be";
    //string& insert (size_t pos, const string& str)
    str.insert(6, str2);
    cout << str << endl;
    //string& insert (size_t pos, const string& str, size_t subpos, size_t sublen)
    str.insert(6, str3, 3, 4);   
    cout << str << endl;
    // string& insert (size_t pos, const char* s, size_t n)
    str.insert(10, "that is cool", 8);  
    cout << str << endl;
    // string& insert (size_t pos, const char* s)
    str.insert(10, "to be ");
    cout << str << endl;
    //string& insert (size_t pos, size_t n, char c);
    str.insert(15, 1, ':');
    cout << str << endl;
    //iterator insert (iterator p, char c)
    string::iterator it = str.insert(str.begin() + 5, ','); 
    cout << str << endl;
    str.insert(str.end(), 3, '.');
    cout << str << endl;
    // void insert (iterator p, InputIterator first, InputIterator last);
    str.insert(it + 2, str3.begin(), str3.begin() + 3); 
    cout << str << endl;
    return 0;
}

6.erase:

Erases part of the string, reducing its length:

翻译:消除string对象部分内容,从而减少其长度

使用,相信大家一看就会了,毕竟已经写过非常多了

7.replace:

Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents:

翻译:从string对象pos位置开始替换len个长度的字符串

#include <string>
int main()
{
    std::string base = "this is a test string.";
    std::string str2 = "n example";
    std::string str3 = "sample phrase";
    std::string str4 = "useful.";
    std::string str = base;           // "this is a test string."
    str.replace(9, 5, str2);          // "this is an example string." (1)
    str.replace(19, 6, str3, 7, 6);     // "this is an example phrase." (2)
    str.replace(8, 10, "just a");     // "this is just a phrase."     (3)
    str.replace(8, 6, "a shorty", 7);  // "this is a short phrase."    (4)
    str.replace(22, 1, 3, '!');        // "this is a short phrase!!!"  (5)
    // Using iterators:                                               0123456789*123456789*
    str.replace(str.begin(), str.end() - 3, str3);                    // "sample phrase!!!"      (1)
    str.replace(str.begin(), str.begin() + 6, "replace");             // "replace phrase!!!"     (3)
    str.replace(str.begin() + 8, str.begin() + 14, "is coolness", 7);    // "replace is cool!!!"    (4)
    str.replace(str.begin() + 12, str.end() - 4, 4, 'o');                // "replace is cooool!!!"  (5)
    str.replace(str.begin() + 11, str.end(), str4.begin(), str4.end());// "replace is useful."    (6)
    std::cout << str << '\n';
    return 0;
}

8.swap

我们对于string类中的swap要和swap函数区分:

对于后一个swap,我们以以下模版来交换不同类型,而string::swap只能交换string对象

int main()
{
	string s1 = "hello world";
	string s2="hello linux", s3="hello windows";
	s1.swap(s2);
	cout << "s1:" << s1 << endl;
	cout << "s2:" << s2 << endl;
	swap(s1, s3);
	cout<< "s1:" << s1 << endl;
	cout<< "s3:" << s3 << endl;
	return 0;
}

结果:

如果我们调用string::swap还需要深拷贝,明显过于复杂,所以,我们更常用的是swap函数,这也是string过于赘余之处。

9.pop_back:

Erases the last character of the string, effectively reducing its length by one

翻译:删除string最后一个字符,对于其有效长度减少1

int main()
{
	string s1("hello string ");
	s1.pop_back();
	cout << s1 << endl;
	s1.pop_back();
	cout << s1 << endl;
	return 0;
}

对于modifiers我们就讲完了,里面是有非常多的是不常用的,知道用法即可,对于常用的大家就要非常清楚了。

二.Member constants

1.nops:

npos is a static member constant value with the greatest possible value for an element of type size_t.

翻译:nops是一个静态成员变量,并且能达到size_t类型的元素的最大可能值

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type

翻译:npos默认是-1,原因在于size_t是一个无符号类型,nops为默认值时,它转换为size_t时为最大值

关于nops重要的点就是这两个,大家一定要熟悉!!!

三.String operations:

1.c_str:

大家看了半天可能都不知道这个是用来干哈的,实际上当我们遇到以下情况时,就是其登场的时候:

int main()
{
	string filename("Test.cpp");
	FILE* fout = fopen(filename.cpp, "r");
	char ch = fgetc(fout);
	while (ch != EOF)
	{
		cout << ch;
		ch = fgetc(fout);
	}
	return 0;
}

报错如下:

.cpp文件无法进行C语言文件读取操作,此时我们就可以用c_str()函数了

该函数解读:

Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
翻译:返回一个指向数组的指针,该数组包含一个以null结尾的字符序列(即C字符串),表示字符串对象的当前值
This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end

翻译:该数组包含了string对象的全部字符并且在结尾加上'\0'

所以,上述错误,我们就可以通过以下修改:

int main()
{
	string filename("Test.cpp");
	FILE* fout = fopen(filename.c_str(), "r");//将filename.cpp修改为filename.c_str()
	char ch = fgetc(fout);
	while (ch != EOF)
	{
		cout << ch;
		ch = fgetc(fout);
	}
	return 0;
}

2.data:

其作用就是获取string对象的内容,如下:

(没啥别的作用,string缺点之一:冗杂)

3.copy:

Copy sequence of characters from string

翻译:对string对象的拷贝

注意下参数意思:

len--拷贝长度    pos拷贝起始位置

int main()
{
	char buffer[20];
	string str("Test string...");
	size_t length = str.copy(buffer, 6, 5);
	buffer[length] = '\0';
	std::cout << "buffer contains: " << buffer << '\n';
	return 0;
}

4.find:

Searches the string for the first occurrence of the sequence specified by its arguments

翻译:在string对象中找到第一次出现的内容(可以为字符/字符串)

该函数关键在于函数参数:

//注意点:const修饰,不要放大权限!!!
//str/s是指要找到字符串,c是要找的字符
//pos是开始查找位置
size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_t n) const;
//n是指查找前n个字符
size_t find (char c, size_t pos = 0) const;
int main()
{
	string str("https://legacy.cplusplus.com/reference/string/string/");
	string sub1, sub2, sub3;
	size_t pos1 = str.find(':');
	sub1 = str.substr(0, pos1 - 0);//substr是我们后面要学的,表示子string对象
	cout << sub1 << endl;	
	size_t pos2 = str.find('/', pos1+3);
	sub2 = str.substr(pos1 + 3, pos2 - (pos1 + 3));
	cout << sub2 << endl;	
	sub3 = str.substr(pos2 + 1);
	cout << sub3 << endl;
	return 0;
}

结果:

4.substr:

Returns a newly constructed string object with its value initialized to a copy of a substring of this object.

翻译:返回一个新的string对象。并且其初始化通过对于string对象的一份子拷贝

5.rfind:

Searches the string for the last occurrence of the sequence specified by its arguments

翻译:在string对象中查找最后一次出现的位置

大体和find相同,不再演示,注意点为:是最后一次出现位置!!!

其他的内容,我们后面再讲,bye!!!

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

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

相关文章

vue前端使用get方式获取api接口数据 亲测

// GET请求示例 axios.get(‘http://127.0.0.1:5005/ReadIDCardInfo’) // 将URL替换为真正的API接口地址 .then(response > { if(response.data.code1){ var jsonDataresponse.data.data; console.log(jsonData); // 输出从API接口返回的数据 } }) .catch(error > { con…

ModStartCMS v8.1.0 图片前端压缩,抖音授权登录

ModStart 是一个基于 Laravel 模块化极速开发框架。模块市场拥有丰富的功能应用&#xff0c;支持后台一键快速安装&#xff0c;让开发者能快的实现业务功能开发。 系统完全开源&#xff0c;基于 Apache 2.0 开源协议&#xff0c;免费且不限制商业使用。 功能特性 丰富的模块市…

电脑合集检测工具箱,图吧工具箱软件推荐

今天最软库给大家体验的是电脑检测工具箱。 图吧工具箱&#xff0c;是开源、免费、绿色、纯净的硬件检测工具合集&#xff0c;专为所有计算机硬件极客、DIY爱好者、各路大神及小白制作。集成大量常见硬件检测、评分工具&#xff0c;一键下载、方便使用。 不忘初心&#xff0c;始…

leetcode:860.柠檬水找零

题意&#xff1a;按照支付顺序&#xff0c;进行支付&#xff0c;能够正确找零。 解题思路&#xff1a;贪心策略&#xff1a;针对支付20的客人&#xff0c;优先选择消耗10而不是消耗5&#xff0c;因为5可以用来找零10或20. 代码实现&#xff1a;有三种情况&#xff08;代表三种…

Docker本地部署GPT聊天机器人并实现公网远程访问

文章目录 前言1. 拉取相关的Docker镜像2. 运行Ollama 镜像3. 运行Chatbot Ollama镜像4. 本地访问5. 群晖安装Cpolar6. 配置公网地址7. 公网访问8. 固定公网地址9. 结语 前言 随着ChatGPT 和open Sora 的热度剧增,大语言模型时代,开启了AI新篇章,大语言模型的应用非常广泛&…

Oracle 直接路径插入(Direct-Path Insert)

直接路径插入&#xff08;Direct Path Insert&#xff09;是Oracle一种数据加载提速技术&#xff0c;可以在使用insert语句或SQL*Loader工具大批量加载数据时使用。直接路径插入处理策略与普通insert语句完全不同&#xff0c;Oracle会通过牺牲空间&#xff0c;安全性&#xff0…

什么是VR紧急情况模拟|消防应急虚拟展馆|VR游戏体验馆加盟

VR紧急情况模拟是利用虚拟现实&#xff08;Virtual Reality&#xff0c;简称VR&#xff09;技术来模拟各种紧急情况和应急场景的训练和演练。通过VR技术&#xff0c;用户可以身临其境地体验各种紧急情况&#xff0c;如火灾、地震、交通事故等&#xff0c;以及应对这些紧急情况的…

1.1 创建第一个vue项目

cmd命令窗口运行 vue init webpack hellovue 注意&#xff0c;hellovue是项目名称&#xff0c;项目名称不能保存大写字母否者会报错 Sorry, name can no longer contain capital letters. 运行设个命令的时候可能会报错&#xff0c;根据提示先运行 npm i -g vue/cli-init …

使用Axure RP并配置IIS服务结合内网穿透实现公网访问本地HTML原型页面

文章目录 前言1.在AxureRP中生成HTML文件2.配置IIS服务3.添加防火墙安全策略4.使用cpolar内网穿透实现公网访问4.1 登录cpolar web ui管理界面4.2 启动website隧道4.3 获取公网URL地址4.4. 公网远程访问内网web站点4.5 配置固定二级子域名公网访问内网web站点4.5.1创建一条固定…

ardupilot 及PX4姿态误差计算算法对比分析

目录 文章目录 目录摘要1.APM姿态误差计算算法2.PX4姿态误差计算算法3.结论摘要 本节主要记录ardupilot 及PX4姿态误差计算算法差异对比过程,欢迎批评指正。 备注: 1.创作不易,有问题急时反馈 2.需要理解四元物理含义、叉乘及点乘含义、方向余弦矩阵含义、四元数乘法物理含…

32单片机基础:EXTI外部中断

本节是STM32的外部中断系统和外部中断。 中断系统是管理和执行中断的逻辑结构&#xff0c;外部中断是总多能产生中断的外设之一&#xff0c; 所以本节借助外部中断学习一下中断系统。 下图灰色的&#xff0c;是内核的中断&#xff0c;比如第一个&#xff0c;当产生复位事件时…

枚举(蓝桥练习)

目录 一、枚举算法介绍 二、解空间的类型 三、循环枚举解空间 四、例题 &#xff08;一、反倍数&#xff09; &#xff08;二、特别数的和&#xff09; &#xff08;三、找到最多的数&#xff09; &#xff08;四、小蓝的漆房&#xff09; &#xff08;五、小蓝和小桥的…

Visual Studio:指针和固定大小缓冲区只能在不安全的上下文中使用、 设置允许使用不安全代码(unsafe)

问题描述: 指针和固定大小缓冲区只能在不安全的上下文中使用 解决方案&#xff1a; 1、解决方案资源管理器-》选择项目-》右键-》属性 2、在生成窗口中&#xff0c;勾选“允许不安全代码” 3、再次“生成解决方案”即可

THINKPHP 跨域报错解决方案

报错&#xff1a;has been blocked by CORS policy: Response to preflight request doesnt pass access control check: No Access-Control-Allow-Origin header is present on the requested resource. 环境&#xff1a;thinkphp6 nginx 今天和VUE配合调用接口的时候发现跨…

【MySQL】MySQL数据管理——DDL数据操作语言(数据表)

目录 创建数据表语法列类型字段属性SQL示例创建学生表 查看表和查看表的定义表类型设置表的类型 面试题&#xff1a;MyISAM和InnoDB的区别设置表的字符集删除表语法示例 修改表修改表名语法示例 添加字段语法示例 修改字段语法示例 删除字段语法示例 数据完整性实体完整性域完整…

Window系统部署Z-blog并结合内网穿透实现远程访问本地博客站点

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

基于光流法以及背景减除法的降雪检测项目知识点总结

项目总结目录 一、算法部分1.光流法部分知识点2.python代码与大华摄像头之间的实时调用3.两个方法的代码 一、算法部分 1.光流法部分知识点 像素坐标系与直角坐标系之间的转换&#xff0c;之后计算角度。 其中光流法通过判断运动目标的角度来识别是否为降雪&#xff0c;通过…

VS2019 - 未启用调试

在昨天的工作中&#xff0c;遇到了下面的报错&#xff0c;提示的我感觉很莫名其妙&#xff0c;最后找到了解法&#xff0c;记录一下。 弹窗提示 原因 修改了Web.config文件&#xff0c;并且没有保存&#xff0c;也没关闭已经打开的Web.config文件。 解决方案 保存并没关闭已…

部分卷积与FasterNet模型详解

简介 论文原址&#xff1a;2023CVPR&#xff1a;https://arxiv.org/pdf/2303.03667.pdf 代码仓库&#xff1a;GitHub - JierunChen/FasterNet: [CVPR 2023] Code for PConv and FasterNet 为了设计快速神经网络&#xff0c;很多工作都集中于减少浮点运算&#xff08;FLOPs&a…

(libusb) usb口自动刷新

文章目录 libusb自动刷新程序Code目录结构Code项目文件usb包code包 效果描述重置reset热拔插使用 END libusb 在操作USB相关内容时&#xff0c;有一个比较著名的库就是libusb。 官方网址&#xff1a;libusb 下载&#xff1a; 下载源码官方编好的库github&#xff1a;Release…