Day 22 C++ STL常用容器——string容器

string容器

  • 概念
  • 本质
  • string和char 区别:
  • 特点
  • string构造函数
      • 构造函数原型
  • string赋值操作
      • 赋值的函数原型
      • 示例
  • string字符串拼接
      • 函数原型:
      • 示例
  • string查找和替换
      • 函数原型
      • 示例
  • string字符串比较
      • 比较方式 字符串比较是按字符的ASCII码进行对比
      • 函数原型
      • 示例
  • string字符存取
      • string中**单个字符存取方式**有两种
          • 使用下标(`[]`)运算符
          • 使用`at()`函数
  • string插入和删除
      • 函数原型
      • 示例
  • string子串
      • 函数原型
      • 示例

概念

在C++中是C++标准库提供的一个字符串类模板。它被设计为更高级、更方便和更安全的字符串处理工具,相比于C风格的字符串数组,它提供了更多的功能和便捷的操作。

string类封装了一系列成员函数来操作字符串,这些成员函数包括字符串的创建、复制、拼接、查找、替换等等。它还提供了运算符重载,使得字符串的操作和使用更加直观和简洁。

当使用string时,不需要手动管理字符串的内存,它会自动处理内存的分配和释放。此外,string还提供了对字符串的边界检查,避免了缓冲区溢出等问题,提高了代码的安全性。

本质

string本质上是一个类

由于string是一个类,所以它可以使用类的特性,如构造函数、析构函数、拷贝构造函数、赋值运算符重载等。这些特性使得string类更易于使用和管理字符串数据。

综上所述,string是C++风格的字符串,本质上是一个类,在C++中广泛用于处理和操作字符串数据,提供了便利、安全和高级的字符串处理功能。

string和char 区别:

  • char * 是一个指针
  • string是一个类,类内部封装了char*,管理这个字符串,是一个char*型的容器
  • 内存管理:string类封装了字符串的内存管理,它会自动分配和释放内存,并且可以动态调整字符串的大小。而char*需要手动分配和释放内存,并且在操作字符串时需要确保足够的内存空间。
  • 字符串长度::string对象可以存储任意长度的字符串,并且可以使用成员函数获取字符串的长度。而char*作为一个字符数组指针,需要以空字符(‘\0’)作为字符串的结尾,使用标准库函数如strlen()来获取其长度。
  • 操作和修改:string提供了一系列成员函数来进行字符串的操作和修改,如拼接、插入、删除、查找、替换等。而char*需要使用标准库函数来进行类似的操作,如strcat()、strcpy()、strncpy()等。
  • 安全性:由于string类内部封装了字符串的操作和内存管理,对于越界访问和缓冲区溢出等问题有更好的安全性。而char*需要手动确保字符串操作的安全,容易发生内存访问错误。

特点

  • 封装了一些成员方法:std::string类提供了许多有用的成员方法来操作字符串,包括查找(find())、拷贝(copy())、删除(erase())、替换(replace())、插入(insert())等。这些成员方法使得字符串的操作更为便捷和灵活。

  • 内存管理:std::string对象会自动管理分配给它的内存空间,包括创建、扩展和释放。这意味着你无需手动管理字符串的内存,避免了复制越界和取值越界等问题。类内部会负责处理内存的分配和释放,大大提高了程序的安全性和可靠性。

string构造函数

构造函数原型

string(const char* s);
使用以空字符(‘\0’)结尾的C风格字符串s来初始化字符串对象。
例如:std::string str(“Hello”);

string(const string& str);
使用另一个std::string对象str来初始化字符串对象。
例如:std::string str1(“Hello”); std::string str2(str1);

string(int n, char c);
使用字符c重复n次初始化字符串对象。
例如:std::string str(5, ‘a’); // str的值为 “aaaaa”

string();
创建一个空的字符串对象。
例如:std::string str;

string赋值操作

赋值的函数原型

  • string& operator=(const char* s); //char*类型字符串 赋值给当前的字符串
  • string& operator=(const string &s); //把字符串s赋给当前的字符串
  • string& operator=(char c); //字符赋值给当前的字符串
  • string& assign(const char *s); //把字符串s赋给当前的字符串
  • string& assign(const char *s, int n); //把字符串s的前n个字符赋给当前的字符串
  • string& assign(const string &s); //把字符串s赋给当前字符串
  • string& assign(int n, char c); //用n个字符c赋给当前字符串

示例

std::string str1;
str1 = "Hello";  // 使用const char*类型字符串进行赋值
// 等价于 str1.operator=("Hello");std::string str2;
std::string anotherStr = "World";
str2 = anotherStr;  // 使用另一个std::string对象进行赋值
// 等价于 str2.operator=(anotherStr);std::string str3;
str3 = 'A';  // 使用字符进行赋值
// 等价于 str3.operator=('A');std::string str4;
str4.assign("Hello");  // 使用const char*类型字符串进行赋值
// 等价于 str4.assign("Hello", std::strlen("Hello"));std::string str5;
str5.assign("Hello", 3);  // 使用字符串的前3个字符进行赋值
// 等价于 str5.assign("Hel", 3);std::string str6;
std::string anotherStr2 = "World";
str6.assign(anotherStr2);  // 使用另一个std::string对象进行赋值
// 等价于 str6.assign(anotherStr2);std::string str7;
str7.assign(5, 'X');  // 使用5个字符'X'进行赋值
// 等价于 str7.assign("XXXXX", std::strlen("XXXXX"));

string字符串拼接

字符串末尾拼接字符串

函数原型:

  • string& operator+=(const char* str); //重载+=操作符
  • string& operator+=(const char c); //重载+=操作符
  • string& operator+=(const string& str); //重载+=操作符
  • string& append(const char *s); //把字符串s连接到当前字符串结尾
  • string& append(const char *s, int n); //把字符串s的前n个字符连接到当前字符串结尾
  • string& append(const string &s); // 同 operator+=(const string& str)
  • string& append(const string &s, int pos, int n); //字符串s中从pos开始的n个字符连接到字符串结尾

示例

#include <iostream>
#include <string>int main() {std::string str = "Hello";// 使用 operator+= 将 C 风格字符串拼接到 str 的末尾str += " World";std::cout << str << std::endl;  // 输出:Hello World// 使用 append 将字符串的前 n 个字符拼接到 str 的末尾std::string s1 = "Welcome";str.append(s1, 3, 4);std::cout << str << std::endl;  // 输出:Hello Worldcome// 使用 operator+= 将另一个 std::string 对象拼接到 str 的末尾std::string s2 = "!";str += s2;std::cout << str << std::endl;  // 输出:Hello Worldcome!return 0;
}

string查找和替换

查找:查找指定字符串是否存在
替换:在指定的位置替换字符串

函数原型

  • int find(const string& str, int pos = 0) const; //查找str第一次出现位置,从pos开始查找

  • int find(const char* s, int pos = 0) const; //查找s第一次出现位置,从pos开始查找

  • int find(const char* s, int pos, int n) const; //从pos位置查找s的前n个字符第一次位置

  • int find(const char c, int pos = 0) const; //查找字符c第一次出现位置

  • int rfind(const string& str, int pos = npos) const; //查找str最后一次位置,从pos开始查找

  • int rfind(const char* s, int pos = npos) const; //查找s最后一次出现位置,从pos开始查找

  • int rfind(const char* s, int pos, int n) const; //从pos查找s的前n个字符最后一次位置

  • int rfind(const char c, int pos = 0) const; //查找字符c最后一次出现位置

  • string& replace(int pos, int n, const string& str); //替换从pos开始n个字符为字符串str

  • string& replace(int pos, int n,const char* s); //替换从pos开始的n个字符为字符串s

注意:函数声明中的 const 关键字表示该成员函数不会修改类的成员变量

示例

#include <iostream>
#include <string>int main() {std::string str = "Hello World";// 使用 find 函数查找字符串是否存在int pos1 = str.find("World");if (pos1 != std::string::npos) {std::cout << "Found at position: " << pos1 << std::endl;} else {std::cout << "Not found" << std::endl;}// 使用 rfind 函数从后向前查找字符串最后一次出现的位置int pos2 = str.rfind("l");if (pos2 != std::string::npos) {std::cout << "Last found at position: " << pos2 << std::endl;} else {std::cout << "Not found" << std::endl;}// 使用 replace 函数替换指定位置的字符串std::string repl = "Everyone";str.replace(6, 5, repl);std::cout << "After replacement: " << str << std::endl;return 0;
}

string字符串比较

字符串之间的比较

比较方式 字符串比较是按字符的ASCII码进行对比

= 返回 0

> 返回 1

< 返回 -1

函数原型

  • int compare(const string &s) const; //与字符串s比较
  • int compare(const char *s) const; //与字符串s比较

示例

#include <iostream>
#include <string>int main() {std::string str1 = "Hello";std::string str2 = "World";// 使用 compare 函数比较两个字符串int result1 = str1.compare(str2);if (result1 < 0) {std::cout << str1 << " is less than " << str2 << std::endl;} else if (result1 > 0) {std::cout << str1 << " is greater than " << str2 << std::endl;} else {std::cout << str1 << " is equal to " << str2 << std::endl;}// 使用 compare 函数比较字符串和字符数组const char* str3 = "Hello";int result2 = str1.compare(str3);if (result2 < 0) {std::cout << str1 << " is less than " << str3 << std::endl;} else if (result2 > 0) {std::cout << str1 << " is greater than " << str3 << std::endl;} else {std::cout << str1 << " is equal to " << str3 << std::endl;}return 0;
}

string字符存取

string中单个字符存取方式有两种

  • char& operator[](int n); //通过[]方式取字符
  • char& at(int n); //通过at方法获取字符
使用下标([])运算符

可以使用下标运算符来直接访问字符串中的单个字符。下标从0开始,表示第一个字符,依次递增。
例如,str[0]表示字符串str中的第一个字符。

示例

#include <iostream>
#include <string>int main() {std::string str = "Hello, World!";// 使用下标运算符访问单个字符char ch1 = str[0];   // 获取字符串的第一个字符char ch2 = str[7];   // 获取字符串的第八个字符std::cout << "ch1: " << ch1 << std::endl;std::cout << "ch2: " << ch2 << std::endl;return 0;
}

在上述示例中,我们创建了一个字符串对象str,将其初始化为"Hello, World!"。然后,使用下标运算符[]获取字符串中的第一个字符和第八个字符,并分别将它们存储在变量ch1ch2中。最后,我们使用std::cout输出这两个字符。

使用at()函数

另一种访问单个字符的方式是使用at()函数。at()函数与下标运算符类似,可以用来访问指定位置的字符。与下标运算符不同的是,at()函数会进行边界检查,如果访问位置超出字符串的范围,会抛出一个std::out_of_range异常。

示例

#include <iostream>
#include <string>int main() {std::string str = "Hello, World!";// 使用at()函数访问单个字符char ch1 = str.at(0);   // 获取字符串的第一个字符char ch2 = str.at(7);   // 获取字符串的第八个字符std::cout << "ch1: " << ch1 << std::endl;std::cout << "ch2: " << ch2 << std::endl;return 0;
}

在上述示例中,我们使用at()函数来获取字符串中的第一个字符和第八个字符,并将它们分别存储在变量ch1ch2中。然后,我们使用std::cout输出这两个字符。

无论是使用下标运算符还是at()函数,都可以用来访问和修改字符串中的单个字符。但需要注意的是,如果使用下标运算符访问超出字符串范围的位置,程序可能会发生未定义行为,因此在访问字符之前最好先检查字符串的长度。

string插入和删除

对string字符串进行插入和删除字符操作

函数原型

  • string& insert(int pos, const char* s); //插入字符串
  • string& insert(int pos, const string& str); //插入字符串
  • string& insert(int pos, int n, char c); //在指定位置插入n个字符c
  • string& erase(int pos, int n = npos); //删除从Pos开始的n个字符

示例

#include <iostream>
#include <string>int main() {std::string str = "Hello";// 使用 insert 在指定位置插入字符串str.insert(1, "123");std::cout << str << std::endl;  // 输出:H123ello// 使用 erase 删除指定位置的字符str.erase(2, 3);std::cout << str << std::endl;  // 输出:H1elloreturn 0;
}

该示例演示了如何对字符串进行插入和删除字符操作。使用 insert
函数可以在指定位置插入字符串,这里在位置1插入字符串"123",结果为"H123ello"。使用 erase
函数可以删除指定位置的字符,这里删除位置2开始的3个字符,结果为"H1ello"。

string子串

从字符串中获取想要的子串

函数原型

  • string substr(int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串

示例

#include <iostream>
#include <string>int main() {std::string str = "Hello, World!";// 使用 substr 获取子串std::string sub1 = str.substr(7);  // 从位置7开始直到字符串末尾的子串std::cout << sub1 << std::endl;    // 输出:World!std::string sub2 = str.substr(7, 5);  // 从位置7开始的5个字符组成的子串std::cout << sub2 << std::endl;       // 输出:Worldreturn 0;
}

该示例演示了如何从字符串中获取子串。使用 substr 函数可以根据指定的起始位置和长度获取子串。在示例中,通过 str.substr(7) 获取从位置7开始直到字符串末尾的子串,结果为"World!“。通过 str.substr(7, 5)
获取从位置7开始长度为5的子串,结果为"World”。

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

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

相关文章

Dockerfile构建LNMP镜像

建立工作目录 [rootlocalhost ~]# mkdir lnmp [rootlocalhost ~]# cd lnmp/ 编写Dockerfile文件 [rootlocalhost lnmp]# vim Dockerfile [rootlocalhost lnmp]# ll 总用量 4 -rw-r--r--. 1 root root 774 8月 3 14:54 Dockerfile [rootlocalhost lnmp]# vim Dockerfile #基础…

Linux常见问题-打deb包流程

Deb打包目的&#xff1a;将程序打包成.deb格式是为了在Debian和Ubuntu等基于Debian的Linux发行版上进行方便的安装和管理。以下是一个简要的流程&#xff0c;以一个输出 "Hello World" 的C程序为例。 1 准备工作 确保你的系统安装了构建工具&#xff0c;如g&#x…

【Spring Boot】(三)深入理解 Spring Boot 日志

文章目录 前言一、日志文件的作用二、Spring Boot 中的日志2.1 查看输出的日志信息2.2 日志格式二、Spring Boot 中的日志2.1 查看输出的日志信息2.2 日志格式 三、自定义日志输出3.1 日志框架3.2 日志对象的获取3.3 使用日志对象打印日志 四、日志级别4.1 日志级别的作用4.2 日…

人到中年不得已,保温杯里泡枸杞--送程序员

目录 一&#xff1a;你现在身体的体能状况如何&#xff1f;你有身体焦虑吗&#xff1f; 二&#xff1a;如何保持规律性运动&#xff1f; 三&#xff1a;你有哪些健康生活的好习惯&#xff1f; 大厂裁员&#xff0c;称35岁以后体能下滑&#xff0c;无法继续高效率地完成工作&…

Gof23设计模式之组合模式

1.定义 ​组合模式又名部分整体模式&#xff0c;是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象&#xff0c;用来表示部分以及整体层次。这种类型的设计模式属于结构型模式&#xff0c;它创建了对象组的树形结构。 2.结构 组合模式主要包含三种…

深入理解Spring MVC中的@ResponseBody注解

引言 在现代的Web应用开发中&#xff0c;数据的传递和交互是不可或缺的一部分。Spring MVC作为一个强大的框架&#xff0c;在处理客户端请求和响应时&#xff0c;提供了许多注解来简化开发过程。其中&#xff0c;ResponseBody注解在处理方法的返回值时起到了关键作用&#xff0…

Android 从其他xml文件中获取View组件数据

问题 Android Studio 我想在 trace.java 从setting.java绑定的页面activity_setting.xml中 的editview中获取数据 解决方案 仅适用于 在同一应用的不同组件之间共享数据 在 SettingActivity.java 中&#xff0c;当用户准备离开当前活动时&#xff0c;可以将 EditText 中的数…

无涯教程-Perl - endgrent函数

描述 此功能告诉系统您不再希望使用getgrent从groups文件中读取条目。 语法 以下是此函数的简单语法- endgrent返回值 此函数不返回任何值。 Perl 中的 endgrent函数 - 无涯教程网无涯教程网提供描述此功能告诉系统您不再希望使用getgrent从groups文件中读取条目。 语法以…

UI Automator 常用 API 整理

主要类&#xff1a; import android.support.test.uiautomator.UiDevice;作用&#xff1a;设备封装类&#xff0c;测试过程中获取设备信息和设备交互。 import android.support.test.uiautomator.UiObject;作用&#xff1a;所有控件抽象&#xff0c;用于表示一个Android控件。…

STM32——LED内容补充(寄存器点灯及反转的原理)

文章目录 点灯流程开时钟配置IO关灯操作灯反转宏定义最后给自己说 本篇文章使用的是STM32F103xC系列的芯片&#xff0c;四个led灯在PE2,PE3,PE4,PE5上连接 点灯流程 1.开时钟 2.配置IO口 &#xff08;1&#xff09;清零指定寄存器位 &#xff08;2&#xff09;设置模式为推挽输…

最新2024届【海康威视】内推码【GTK3B6】

最新2024届【海康威视】内推码【GTK3B6】 【内推码使用方法】 1.请学弟学妹们登录校招官网&#xff0c;选择岗位投递简历&#xff1b; 2.投递过程中填写内推码完成内推步骤&#xff0c;即可获得内推特权。 内推码&#xff1a;GTK3B6 内推码&#xff1a;GTK3B6 内推码&…

【广州华锐视点】海上石油钻井VR在线实训平台

随着科技的不断发展&#xff0c;VR元宇宙平台已经成为了越来越多领域的培训工具。在海上石油钻井实训中&#xff0c;VR元宇宙平台也能够发挥重要的作用&#xff0c;为学员提供更加真实、直观的培训体验。 首先&#xff0c;VR元宇宙平台可以模拟真实的海上钻井作业环境。通过VR眼…

【嵌入式学习笔记】嵌入式入门6——定时器TIMER

1.定时器概述 1.1.软件定时原理 使用纯软件&#xff08;CPU死等&#xff09;的方式实现定时&#xff08;延时&#xff09;功能有诸多缺点&#xff0c;如CPU死等、延时不精准。 void delay_us(uint32_t us) {us * 72;while(us--); }1.2.定时器定时原理 使用精准的时基&#…

uniapp点击图片放大预览

阐述 有些时候我们在用uniapp显示图片时&#xff0c;有的不宜全部显示到屏幕上&#xff0c;uniapp提供了一个非常好用的api。 实现方式如下&#xff1a; <template><view class"content"><image class"logo" src"/static/images/a.…

Unity限制在一个范围内移动

Unity限制在一个范围内移动 这个例子中&#xff0c;我们学习Vector3.ClampMagnitude的用法&#xff0c;限制小球在范围内移动。 在地图上放了一个小球&#xff0c;让他移动&#xff0c;但是不想让他掉下去&#xff0c;限制在一个球星范围内&#xff0c;就好像绳子拴住了一样&…

12. Redis分布式高可用集群搭建

文章目录 Redis分布式高可用集群搭建一、redis集群有三种方式&#xff1a;1. 主从模式2. 哨兵3. 集群&#xff08;master-cluster&#xff09; 二、基于centos7操作系统操做1. 关闭防火墙&#xff0c;三台机器都执行2. hostname修改&#xff0c;三台机器都执行,这一步是为了在内…

ChatGPT 作为 Python 编程助手

推荐&#xff1a;使用 NSDT场景编辑器 助你快速搭建可编辑的3D应用场景 简单的数据处理脚本 我认为一个好的起点是某种数据处理脚本。由于我打算让 ChatGPT 之后使用各种 Python 库编写一些机器学习脚本&#xff0c;这似乎是一个合理的起点。 目标 首先&#xff0c;我想尝试…

php8.2编译安装swoole v5.0

515 unzip swoole-v5.0.3.zip 516 cd swoole-v5.0.3 517 /usr/local/php82/bin/phpize 519 ./configure --with-php-config/usr/local/php82/bin/php-config 520 make 521 make install 加入swoole扩展 522 vim /usr/local/php82/lib/php.ini 编译安装php8…

设计模式——工厂模式

工厂模式是Java中常用的设计模式&#xff0c;提供了一种创建对象的最佳方式&#xff0c;工厂模式是将对象实例化的过程封装在了工厂类中&#xff0c;然后对外提供一个方法用来获取对象 1.简单工厂模式 简单工厂不属于设计模式之一&#xff0c;因为它没有遵守开闭原则&#xff…

kubeadml 安装 k8s

目录 一&#xff1a;kubeadml 安装 k8s 1、网络环境 2、 环境准备 3、 所有节点安装docker 4、所有节点安装kubeadm&#xff0c;kubelet和kubectl ​5、部署K8S集群 6、测试 二&#xff1a; 部署 Dashboard 一&#xff1a;kubeadml 安装 k8s 1、网络环境 master&am…