【C++】string类(下)

news2024/9/21 4:32:14

文章目录

    • 1.迭代器(正向遍历)
      • begin有两个版本
    • 2.反向迭代器(反向遍历)
      • rbegin由两个版本
    • 3. at
    • 4. insert ——头插
      • 在pos位置前插入一个字符串
      • 在pos位置前插入n个字符
      • 在迭代器前插入一个字符
    • 5. erase
      • 从pos位置开始删除len个字符
      • 从迭代器位置开始删除
    • 6. replace——替换
      • 从pos位置开始的n个字符替换成想要的字符
    • 7. find ——查找
      • 例题 替换空格
    • 8. swap ——交换
    • 9. c_str
    • 10. substr
    • 11. getline

1.迭代器(正向遍历)

#include<iostream>
#include<string>
using namespace std;
//迭代器
int main()
{
    string s("hello world");
    string::iterator it = s.begin();//遍历字符串
    while (it != s.end())
    {
        cout << *it << " ";
        it++;
    }
    return 0;
}

在这里插入图片描述

  • s.begin()返回指向第一个位置的指针,s.end()返回指向最后一个位置的下一个的指针

begin有两个版本

#include<iostream>
#include<string>
using namespace std;
void func(const string& s1)
{
    string::iterator it = s1.begin();//会报错
    while (it != s1.end())
    {
        cout << *it << endl;
        it++;
    }
}
int main()
{
    string s("hello world");
    func(s);
    return 0;
}

当我们想要在一个函数中实现迭代器,发现会报错是因为begin一共有两个版本
在这里插入图片描述

  • 当函数的参数为const时,需要返回const的迭代器

#include<iostream>
#include<string>
using namespace std;
void func(const string& s1)
{
    string::const_iterator it = s1.begin();//会报错
    while (it != s1.end())
    {
        //*it = 2; //由于it可以看作指针,由const修饰后,it指向的内容不能被修改
        cout << *it << endl;
        it++;
    }
}
int main()
{
    string s("hello world");
    func(s);
    return 0;
}
  • it可以看作指针,由const修饰后,it指向的内容不能被修改
  • 只能遍历和读容器的数据,不能写

2.反向迭代器(反向遍历)

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

int main()
{
    //F反向迭代器
    string s("hello world");
    string::reverse_iterator rit = s.rbegin();
    while (rit != s.rend())
    {
        cout << *rit <<" "; //d l r o w   o l l e h
        rit++;
    }
    return 0;
}

在这里插入图片描述

  • s.rbegin()返回指向最后一个位置的指针,s.rend()返回指向第一个位置前一个的指针

rbegin由两个版本

在这里插入图片描述

  • 同样反向迭代器的rbegin也存在两个版本,一个不用const和一个用const修饰的
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("hello");
    string::const_reverse_iterator rit = s.rbegin();
    while (rit != s.rend())
    {
        //*rit = 2; 会报错
        cout << *rit << endl;
        *rit++;
    }
    return 0;
}
  • rit可以看作指针,由const修饰后,rit指向的内容不能被修改
  • 与it的const版本特性一致,只能遍历和读容器的数据,不能写

3. at

  • 返回pos位置的字符
    在这里插入图片描述
  • 如果访问越界,opertaor[ ]会直接报错

在这里插入图片描述

  • 访问越界,at会抛异常

4. insert ——头插

在pos位置前插入一个字符串

  • string& insert (size_t pos, const string& str);
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("world");
    s.insert(0, "hello");//0位置前插入字符串
    cout << s << endl;//helloworld
    return 0;
}

在pos位置前插入n个字符

  • string& insert (size_t pos, size_t n, char c);
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("world");
    s.insert(0,1,'!');//pos位置插入1个字符!
    cout << s << endl;
    return 0;
}

在迭代器前插入一个字符

  • iterator insert (iterator p, char c);
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("world1");
    s.insert(s.begin()+5, '!');
    cout << s << endl;//world!1
    return 0;
}

s.begin()代表开头的位置,s.begin()+5代表1的位置,在1之前插入字符!

5. erase

从pos位置开始删除len个字符

  • string& erase (size_t pos = 0, size_t len = npos);
    npos代表缺省值,即整数最大值
    若len长度大于字符pos位置后的长度或者不给len值自动使用npos, 则pos位置之后全部删除
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("hello world");
    s.erase(0, 5);
        s.erase(2);//2位置后全部删除
    cout << s << endl;// world
}
  • 0位置开始,删除5个字符

从迭代器位置开始删除

  • iterator erase (iterator p);
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("hello world");
    s.erase(s.begin()+1);
    cout << s << endl;//hllo world
}

从迭代器位置开始删除一个字符

6. replace——替换

从pos位置开始的n个字符替换成想要的字符

  • string& replace (size_t pos, size_t len, const char* s);
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("hello world");
    s.replace(5, 1, "%%d");
    cout << s << endl;
}

从下标为5的位置开始的1个字符 替换成%%d

7. find ——查找

  • size_t find (char c, size_t pos = 0) const;
  • 查找字符,找到了返回当前pos位置的下标,没有找到就返回npos(整形最大值)

例题 替换空格

将空格替换成%20

#include<iostream>
#include<string>
using namespace std;
//替换空格问题
int main()
{
    string s("i love you");
    int i = 0;
    int sum = 0;
    for (i = 0; i < s.size(); i++)
    {
        sum++;
    }
    s.reserve(s.size() + 2 * sum);//提前开空间,避免replace扩容
    size_t pos = s.find(' ');
    while (pos != string::npos)
    {
        s.replace(pos, 1, "%20");
        pos = s.find(' ', pos + 3);//跳过上一次已经替换过的空格
    }
    cout << s << endl;
    return 0;
}
  • 通过使用reserve提前扩容,以及跳过上一次已经替换的空格进行效率提升

8. swap ——交换

  • void swap (string& str);
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s1("abc");
    string s2("wer");
    s1.swap(s2);//string类中swap
    cout << s1 << endl;
    cout << s2 << endl;
    swap(s1, s2);//类模板中的swap
    cout << s1 << endl;
    cout << s2 << endl;
    return 0;
}

string类中swap与类模板中的swap功能相同,
但string类的swap只能针对string完成交换,而类模板的swap,可以对任意类型完成交换
string类的swap更高效一点,直接修改两者指针的指向

  • 修改s1指针指向原来s2指向的空间,修改s2指针指向原来s1指针指向的空间

9. c_str

  • const char*类型的指针
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string s("hello world");
    cout << s << endl;//自定义类型 运算符重载<<
    cout << s.c_str() << endl;//返回一个const char*指针,按照字符串打印 遇见'\0'结束
    return 0;
}

10. substr

  • 从pos位置取len个字符的子串
  • string substr (size_t pos = 0, size_t len = npos) const;
  • 从后往前查找字符
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string file("test.zip.c");
    size_t pos = file.rfind('.');//倒着查找字符.
    if (pos != string::npos)
    {
        string suffix = file.substr(pos);
        cout << suffix << endl;
    }
    return 0;
}

有可能存在多个.存在,所以从后往前找后缀名

11. getline

  • 用来解决cin遇见空格停止的情况
  • 流提取默认使用空格/换行是多个值之间的分隔符 getline遇到换行结束
  • stream& getline (istream& is, string& str);
#include<iostream>
#include<string>
using namespace std;
int main()
{
    //cin>>s//输入 hello world 错误写法
    getline(cin,s);//正确写法
    return 0;
}

若输入hello world,cin会当成两个值,若想把hello world当成一个整体使用getline

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

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

相关文章

【Linux】进程终止进程等待

文章目录进程创建fork函数初识fork函数返回值写时拷贝fork常规用法fork调用失败的原因进程终止进程退出场景进程常见退出方法进程等待进程等待必要性进程等待的方法wait方法waitpid方法获取子进程status从操作系统层面理解waitpid阻塞状态和非阻塞状态阻塞等待例子:多进程创建和…

设计模式 - 模板方法模式详解

介绍&定义 模板模式&#xff0c;全称是模板方法设计模式&#xff0c;英文是 Template Method Design Pattern。在 GoF 的《设计模式》一书中&#xff0c;它是这么定义的&#xff1a; Define the skeleton of an algorithm in an operation, deferring some steps to subcl…

从辅助驾驶到自动驾驶究竟还有多远?

/ 导读 /现如今&#xff0c;自动驾驶的噱头早已被厂家们放在台面上宣传了太多&#xff0c;小鹏汽车更是在最近宣称要在2023年在中国率先推出全自动驾驶&#xff0c;此言一出更是一石激起千层浪&#xff0c;而业内人士表示针对此类言论早已经见怪不怪了&#xff0c;更何况何小鹏…

计算机网络期末复习汇总(附某高校期末真题试卷)

文章目录一、选择题二、填空题三、名词解析四、简答题五、高校期末真题一、选择题 1、传输延迟时间最小的交换方法是( A ) A.电路交换 B.报文交换 C.分组交换 D.信元交换 2、在OSI七层结构模型中&#xff0c;处于数据链路层与运输层之间的是&#xff08; B&#xff09; A、物…

双代号网络图、双代号时标网络图、单代号网络图精讲

01进度管理—普通双代号网络1.识读、虚箭线(1)网络图的识读&#xff1a;基本组成及逻辑关系&#xff1b;(2)补充虚箭线&#xff1a;共用一个班组、共用一台机械&#xff1b;(3)网络图的基本绘制要求&#xff1a;①只有一个起点及终点&#xff1b;②箭线从小节点编号指向大编号&…

for var in 循环报错

近期对babel进行升级&#xff0c;突然爆出 Property left of ForInStatement expected node to be of a type ["VariableDeclaration","LVal"] but instead got undefined&#xff1b;的错误&#xff0c;不知为何&#xff1b;解决&#xff1a;for(var p in…

数据库如何分库分表

有了主从数据库为啥还需要分库分表 如果一个网站业务快速发展&#xff0c;那这个网站流量也会增加&#xff0c;数据的压力也会随之而来&#xff0c;比如电商系统来说双十一大促对订单数据压力很大&#xff0c;Tps十几万并发量&#xff0c;如果传统的架构&#xff08;一主多从&a…

基于matlab设计x波段机载SAR系统

一、前言此示例说明如何设计在 X 波段工作的合成孔径雷达 &#xff08;SAR&#xff09; 传感器并计算传感器参数。SAR利用雷达天线在目标区域上的运动来提供目标区域的图像。当SAR平台在目标区域上空行进时&#xff0c;当脉冲从雷达天线发送和接收时&#xff0c;会产生合成孔径…

MySQL(一):B+ Tree,索引以及其优点, 索引实战, 聚簇索引和非聚簇索引, 最左匹配,索引失效

文章目录一、B TreeB Tree相比于红黑树的优点1. B树有更低的树高2. B树更符合磁盘访问原理二、MySQL索引2.1 B Tree索引2.2 哈希索引2.3 全文索引2.4 空间数据索引三、索引的优点以及什么时候需要使用索引什么时候需要使用索引四、索引实战建立普通索引建立唯一索引建立主键索引…

FreeRTOS内存管理 | FreeRTOS十五

目录 说明&#xff1a; 一、FreeRTOS内存管理 1.1、动态分配与用户分配内存空间 1.2、标准C库动态分配内存缺点 1.3、FreeRTOS的五种内存管理算法优缺点 1.4、heap_1内存管理算法 1.5、heap_2内存管理算法 1.6、heap_3内存管理算法 1.7、heap_4内存管理算法 1.8、hea…

节能降耗方案-医院能源管理系统平台的研究与应用分析

摘要&#xff1a;综合性医院作为大型公共机构&#xff0c;能耗高的问题日益突出&#xff0c;构建能耗监控平台对医院能耗量化管理以及效果评估已经成为迫切需要。建立智能能耗监控平台&#xff0c;对采集的能耗数据进行分析&#xff0c;实现对医院能耗平台监控&#xff0c;为医…

Server端的Actor,分工非常的明确,但是只将Actor作为一部手机来用,真的合适吗?

这是一篇介绍PowerJob&#xff0c;Server端Actor的文章&#xff0c;如果感兴趣可以请点个关注&#xff0c;大家互相交流一下吧。 server端一共有两个Actor&#xff0c;一个是处理worker传过来的信息&#xff0c;一个是server之间的信息传递。 处理Worker的Actor叫做WorkerRequ…

5、HAL库驱动W25Qxx

一、 SPI通信驱动W25Qxx 1、使用驱动文件快速配置工程代码驱动W25Qxx &#xff08;此驱动文件只适合W25Qxx 16M及以下型号&#xff0c;因为访问地址位数不同&#xff09; 注&#xff1a;本次使用SPI的方式进行访问W25Qxx Flash进行数据读写&#xff0c;关于W25Qxx芯片不会做…

10大主流压力测试工具各有所长,怎么选适合自己的?

市面上流行的压力/负载/性能测试工具多是来自国外&#xff0c;近年来国内的性能测试工具也如雨后春笋崛起。同时由于开发的目的和侧重点不同&#xff0c;其功能也有很大差异&#xff0c;下面就为您简单介绍10款目前最常见的测试产品。 1、kylinTOP测试与监控平台&#xff08;商…

实现一个比ant功能更丰富的Modal组件

普通的modal组件如下&#xff1a; 我们写的modal额外支持&#xff0c;后面没有蒙版&#xff0c;并且Modal框能够拖拽 还支持渲染在文档流里&#xff0c;上面的都是fixed布局&#xff0c;我们这个正常渲染到文档下面&#xff1a; render部分 <RenderDialog{...restState}visi…

Lesson5.2---Python 之 NumPy 切片索引和广播机制

一、切片和索引 ndarray 对象的内容可以通过索引或切片来访问和修改&#xff08;&#xff09;&#xff0c;与 Python 中 list 的切片操作一样。ndarray 数组可以基于 0 - n 的下标进行索引&#xff08;先行后列&#xff0c;都是从 0 开始&#xff09;。 区别在于&#xff1a;数…

代码随想录算法训练营第三十二天 | 122.买卖股票的最佳时机II,55. 跳跃游戏,45.跳跃游戏II

一、参考资料买卖股票的最佳时机IIhttps://programmercarl.com/0122.%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BAII.html 跳跃游戏https://programmercarl.com/0055.%E8%B7%B3%E8%B7%83%E6%B8%B8%E6%88%8F.html 跳跃游戏 IIhttps://pr…

金三银四必备软件测试必问面试题

初级软件测试必问面试题1、你的测试职业发展是什么&#xff1f;测试经验越多&#xff0c;测试能力越高。所以我的职业发展是需要时间积累的&#xff0c;一步步向着高级测试工程师奔去。而且我也有初步的职业规划&#xff0c;前 3 年积累测试经验&#xff0c;按如何做好测试工程…

【数据结构期末例题】

前言 本文是博主自己在准备学校数据结构考试时的总结&#xff0c;各个知识点都贴有对应的详细讲解文章以供大家参考&#xff1b;当然文中还有许许多多的截图&#xff0c;这些是博主对主要内容的摘取&#xff0c;对于那些基础较好的同学可以直接看截图&#xff0c;减少跳转对应文…

声呐学习笔记之波束成形

目录什么是波束什么是波束成形线阵数学推导(均匀排布)什么是波束 和光束一样&#xff0c;当所有波的传播方向都一致时&#xff0c;即形成了波束。工程师利用波束已经有相当久的历史。在二战中&#xff0c;工程师已经将波束利用在雷达中&#xff0c;雷达通过扫描波束方向来探测…