【C++】string类的使用④(字符串操作String operations || 常量成员Member constants)

在这里插入图片描述

🔥个人主页: Forcible Bug Maker
🔥专栏: STL || C++

目录

  • 前言
  • 🔥字符串操作(String operations)
    • ==c_str==
    • ==data==
    • ==get_allocator==
    • ==copy==
    • ==find==
    • ==rfind==
    • ==find_first_of==
    • ==find_last_of==
    • ==find_first_not_of==
    • ==find_last_not_of==
    • ==substr==
    • ==compare==
  • 🔥常量成员(Member constants)
    • ==npos==
  • 结语

前言

本篇博客主要内容:STL库中string的字符串操作(String operations)和常量成员(Member constants)

来到string类的使用第四篇,继续我们的内容,本篇博客将着重介绍如何使用string类提供的接口函数去查找和获取字符串的内容;同时还会讲一个定义在string类中的常量成员(npos)
本篇也将是string类使用的收尾篇。

🔥字符串操作(String operations)

在这里插入图片描述

这些接口函数提供的是一些查找和获取string串内容的功能。

c_str

在这里插入图片描述
const char* c_str() const;
返回一个指向字符串数组(以'\0'结尾)的指针,代表当前string串的内容

同时返回指针指向的字符串中的内容也是不可修改的

使用案例:

// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{std::string str("hello world!");char* cstr = new char[str.length() + 1];strcpy(cstr, str.c_str());printf("%s\n", str.c_str());printf("%s\n", cstr);return 0;
}

在这里插入图片描述

简单来说c_str就是获取一个字符串指针,指向的就是string对量串中的内容。

data

在这里插入图片描述
const char* data() const;
返回一个指向数组的指针。(该数组与string串构成字符相同,不保证字符串数组以'\0'结尾。c_str能保证

使用案例:

// string::data
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{int length;std::string str = "Test string";const char* cstr = "Test string";if (str.length() == strlen(cstr)){cout << "str and cstr have the same length.\n";if (memcmp(cstr, str.data(), str.length()) == 0)cout << "str and cstr have the same content.\n";}return 0;
}

在这里插入图片描述

get_allocator

在这里插入图片描述
allocator_type get_allocator() const;
此函数接口返回一个引用到该字符对象的内存分配器(alloctor)的副本。这个分配器用于管理std::string内部数据的内存分配和释放
通常,你不需要使用此函数,编译器能帮你很好的管理好STL库中内存的分配与释放,除非你需要进行一些高级的,与内存管理相关的操作。

实际中并不常用,故不做过多讲解。

copy

在这里插入图片描述
size_t copy (char* s, size_t len, size_t pos = 0) const;
将一个string串从pos位置开始跨越len个长度的子串内容拷贝到s指向的数组中(子串len的长度包括pos位置的字符)

返回值:从string串中拷贝到s中字符的个数,这个数字可以等于lenlength()-pos(如果string对象串的长度小于pos+len)。

注:这个接口函数**不会在拷贝完的字符串结尾自动加’\0’**。

使用案例:

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

在这里插入图片描述

find

在这里插入图片描述

提供了在string串中按顺序查找某字符和某子串的功能。

(1) string
size_t find (const string& str, size_t pos = 0) const;
从pos位置开始查找string串中是否包含str串。如果有,返回匹配上的下标位置;如果没有,则返回常量成员npos(可以看作是一个很大的值,可以提前看下文末的常量成员内容)。
(2) c-string
size_t find (const char* s, size_t pos = 0) const;
从pos位置开始查找string串中是否包含字符串s。如果有,返回匹配上的下标位置;如果没有,则返回常量成员npos。
(3) buffer
size_t find (const char* s, size_t pos, size_t n) const;
从pos位置开始查找string串中是否包含字符串s的前n个字符组成的子串。如果有,返回匹配上的下标位置;如果没有,则返回常量成员npos。
(4) character
size_t find (char c, size_t pos = 0) const;
从pos位置开始查找string串中是否包字符c。如果有,返回匹配上的下标位置;如果没有,则返回常量成员npos。

使用案例:

// string::find
#include <iostream>       // std::cout
#include <string>         // std::string
using namespace std;
int main()
{string str("There are two needles in this haystack with needles.");string str2("needle");// different member versions of find in the same order as above:size_t found = str.find(str2);if (found != string::npos)cout << "first 'needle' found at: " << found << '\n';found = str.find("needles are small", found + 1, 6);if (found != string::npos)cout << "second 'needle' found at: " << found << '\n';found = str.find("haystack");if (found != string::npos)cout << "'haystack' also found at: " << found << '\n';found = str.find('.');if (found != string::npos)cout << "Period found at: " << found << '\n';// let's replace the first needle:str.replace(str.find(str2), str2.length(), "preposition");cout << str << '\n';return 0;
}

在这里插入图片描述

rfind

在这里插入图片描述

这个函数就是从后往前找的find,功能我就不多做赘述了。

(1) string
size_t rfind (const string& str, size_t pos = npos) const;
(2) c-string
size_t rfind (const char* s, size_t pos = npos) const;
(3) buffer
size_t rfind (const char* s, size_t pos, size_t n) const;
(4) character
size_t rfind (char c, size_t pos = npos) const;

注:当pos被确定时,rfind会忽略任何在pos之后的字符。

使用案例:

// string::rfind
#include <iostream>
#include <string>
#include <cstddef>
using namespace std;
int main()
{string str("The sixth sick sheik's sixth sheep's sick.");string key("sixth");size_t found = str.rfind(key);if (found != string::npos)str.replace(found, key.length(), "seventh");cout << str << '\n';return 0;
}

在这里插入图片描述

find_first_of

在这里插入图片描述

从前往后查找在string串中任何存在于某字符或字符串中的字符

(1) string
size_t find_first_of (const string& str, size_t pos = 0) const;
从pos位置开始查找string串的字符是否存在于str串中。如果存在,返回匹配上的下标位置;如果找到string串的末尾也没有,则返回常量成员npos(可以看作是一个很大的值,可以提前看下文末的常量成员内容)。
(2) c-string
size_t find_first_of (const char* s, size_t pos = 0) const;
从pos位置开始查找string串的字符是否存在于字符串s中。如果存在,返回匹配上的下标位置;如果找到string串的末尾也没有,则返回常量成员npos。
(3) buffer
size_t find_first_of (const char* s, size_t pos, size_t n) const;
从pos位置开始查找string串的字符是否存在于字符串s前n个字符组成的子串中。如果存在,返回匹配上的下标位置;如果找到string串的末尾也没有,则返回常量成员npos。
(4) character
size_t find_first_of (char c, size_t pos = 0) const;
从pos位置开始查找string串的字符是否为字符c。如果存在,返回匹配上的下标位置;如果找到string串的末尾也没有,则返回常量成员npos。

使用案例:

// string::find_first_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t
using namespace std;
int main()
{// 将句子中的元音字母转换成星号(*)string str("Please, replace the vowels in this sentence by asterisks.");size_t found = str.find_first_of("aeiou");while (found != string::npos){str[found] = '*';found = str.find_first_of("aeiou", found + 1);}cout << str << '\n';return 0;
}

在这里插入图片描述

find_last_of

在这里插入图片描述

和find_first_of的功能及其相似,不过此函数是从后往前找

(1) string
size_t find_last_of (const string& str, size_t pos = npos) const;
(2) c-string
size_t find_last_of (const char* s, size_t pos = npos) const;
(3) buffer
size_t find_last_of (const char* s, size_t pos, size_t n) const;
(4) character
size_t find_last_of (char c, size_t pos = npos) const;

使用案例:

// string::find_last_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>         // std::size_t
using namespace std;void SplitFilename(const std::string& str)
{cout << "Splitting: " << str << '\n';size_t found = str.find_last_of("/\\");cout << " path: " << str.substr(0, found) << '\n';cout << " file: " << str.substr(found + 1) << '\n';
}int main()
{string str1("/usr/bin/man");string str2("c:\\windows\\winhelp.exe");SplitFilename(str1);SplitFilename(str2);return 0;
}

在这里插入图片描述

find_first_not_of

在这里插入图片描述

在之前find_first_of的基础上,这个看名字似乎就能理解其功能了。没错这个就是从前往后找string串中任何不存在于某字符或字符串中的字符

string (1)
size_t find_first_not_of (const string& str, size_t pos = 0) const;
c-string (2)
size_t find_first_not_of (const char* s, size_t pos = 0) const;
buffer (3)
size_t find_first_not_of (const char* s, size_t pos, size_t n) const;
character (4)
size_t find_first_not_of (char c, size_t pos = 0) const;

使用案例:

// string::find_first_not_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t
using namespace std;
int main()
{string str("look for non-alphabetic characters...");size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");if (found != string::npos){cout << "The first non-alphabetic character is " << str[found];cout << " at position " << found << '\n';}return 0;
}

在这里插入图片描述

find_last_not_of

在这里插入图片描述

从后往前找string串中任何不存在于某字符或字符串中的字符

string (1)
size_t find_last_not_of (const string& str, size_t pos = npos) const;
c-string (2)
size_t find_last_not_of (const char* s, size_t pos = npos) const;
buffer (3)
size_t find_last_not_of (const char* s, size_t pos, size_t n) const;
character (4)
size_t find_last_not_of (char c, size_t pos = npos) const;

使用案例:

// string::find_last_not_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t
using namespace std;
int main()
{string str("Please, erase trailing white-spaces   \n");string whitespaces(" \t\f\v\n\r");size_t found = str.find_last_not_of(whitespaces);if (found != string::npos)str.erase(found + 1);elsestr.clear();            // str对象串中全为空白cout << '[' << str << "]\n";return 0;
}

在这里插入图片描述

substr

在这里插入图片描述
string substr (size_t pos = 0, size_t len = npos) const;
返回一个由string串pos位置开始跨越len个字符(len过大时就取到string对象末尾)创建的子对象(也是string类型)

使用案例:

// string::substr
#include <iostream>
#include <string>
using namespace std;
int main ()
{string str="We think in generalities, but we live in details.";// (quoting Alfred N. Whitehead)string str2 = str.substr (3,5);     // "think"size_t pos = str.find("live");      // 取"live"在str对象中的位置string str3 = str.substr (pos);     // 取从"live"开始到整个str结尾构造字串给str3cout << str2 << ' ' << str3 << '\n';return 0;
}

在这里插入图片描述

compare

在这里插入图片描述

按字典序规则将string对象(或其字串)和别的字符序列进行比较。和之前非成员函数重载的比较运算符很相似,但其功能更全一些,可以直接进行子串之间的比较

string (1)
int compare (const string& str) const;
substrings (2)
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const;
c-string (3)
int compare (const char* s) const;
int compare (size_t pos, size_t len, const char* s) const;
buffer (4)
int compare (size_t pos, size_t len, const char* s, size_t n) const;

直接上代码案例吧,其实也好懂:

// comparing apples with apples
#include <iostream>
#include <string>
using namespace std;
int main()
{string str1("green apple");string str2("red apple");if (str1.compare(str2) != 0)cout << str1 << " is not " << str2 << '\n';if (str1.compare(6, 5, "apple") == 0)cout << "still, " << str1 << " is an apple\n";if (str2.compare(str2.size() - 5, 5, "apple") == 0)cout << "and " << str2 << " is also an apple\n";if (str1.compare(6, 5, str2, 4, 5) == 0)cout << "therefore, both are apples\n";return 0;
}

在这里插入图片描述

🔥常量成员(Member constants)

在这里插入图片描述

npos

在这里插入图片描述
static const size_t npos = -1;
npos是一个const类型的静态成员常量,表示size_t类型的数据可能取到的最大值

可以通过string::npos获取其值,在上面的很多代码案例中都有用到。

整个值,常被当作缺省参数用在string的很多成员函数中(如len,sublen等),表示取到string对象的末尾。

当它作为返回值被返回时,常被用于表示无匹配项

这个常数被赋值为-1,是因为size_t是一个无符号整型,-1代表的就是无符号整型(size_t)可能取到的最大值。

结语

本篇博客,介绍了关于string的字符串操作,可以查找和获取字符串的相关内容;以及常量成员,表示size_t可能取到的最大值,作为返回值返回时常用于表示无匹配项
string的使用系列到这里就结束了。博主后续还会分享string类的模拟实现以及STL更多的内容,感谢大家的支持。♥

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

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

相关文章

Android 老年模式功能 放大字体

1 配置属性 <attr name"text_size_16" format"dimension"/><attr name"text_size_18" format"dimension"/><attr name"text_size_14" format"dimension"/><attr name"text_size_12&quo…

LVGL移植到ARM开发板(GEC6818)

源码下载&#xff1a;点击跳转 下载好三个文件后&#xff0c;将其解压缩&#xff0c;并合到一个文件夹里面—— 1、修改 Makefile 删除 -Wshift-negative-value 2、修改 main.c 3、修改 lv_drv_conf.h 在lv_drv_conf.h文件屏幕驱动文件刚好与开发板LCD驱动文件一致&#xff0c…

基于 Spring Boot 博客系统开发(六)

基于 Spring Boot 博客系统开发&#xff08;六&#xff09; 本系统是简易的个人博客系统开发&#xff0c;为了更加熟练地掌握 SprIng Boot 框架及相关技术的使用。&#x1f33f;&#x1f33f;&#x1f33f; 基于 Spring Boot 博客系统开发&#xff08;五&#xff09;&#x1f…

区块链媒体发布推广7个的神奇方法助你脱颖而出-华媒舍

区块链技术的发展已经掀起了一场数字革命&#xff0c;引发了全球范围内的热议。在这个充满竞争的市场中&#xff0c;如何让自己的区块链项目脱颖而出&#xff0c;吸引更多的关注和参与呢&#xff1f;下面就为大家介绍7个神奇的区块链媒体发布推广方法&#xff0c;帮助你在激烈的…

实验名称:TCP 连接管理

目录 前言 TCP报文段格式 TCP建立连接 TCP释放连接 实验目的 实验原理 实验步骤 1. 启动WireShark&#xff0c;设置抓包状态 2. 访问指定服务器 &#xff0c;通过Wireshark抓取通信数据报文 3. 分析TCP连接建立的三次握手和连接释放的四次握手过程 原始数据记录 实验…

触摸OpenNJet,云原生世界触手可及

&#x1f308;个人主页: Aileen_0v0 &#x1f525;热门专栏: 华为鸿蒙系统学习|计算机网络|数据结构与算法 ​&#x1f4ab;个人格言:“没有罗马,那就自己创造罗马~” 文章目录 导言OpenNJet云原生引擎介绍云原生平台的介绍优化与创新 为什么选择OpenNJet云原生引擎如何在windo…

转移插槽笔记

4.3.4.转移插槽 我们要将num存储到7004节点&#xff0c;因此需要先看看num的插槽是多少&#xff1a; 如上图所示&#xff0c;num的插槽为2765. 我们可以将0~3000的插槽从7001转移到7004&#xff0c;命令格式如下&#xff1a; 具体命令如下&#xff1a; 建立连接&#xff1a;…

Office之Word应用(二)

一、页眉添加文件名称和页码 1、双击页眉&#xff0c;点击“页眉-空白&#xff08;三栏&#xff09;” 2、删掉第一处&#xff08;鼠标放在上面就会选中&#xff0c;Enter即可&#xff09;&#xff0c;第二处输入文档名称&#xff0c;第三处插入页码。 注&#xff1a;插入页码时…

鲁棒控制问题描述

复杂的合成问题成为一个具有特殊结构控制器的设计问题。 H无穷范数&#xff08;H∞ norm&#xff09;&#xff1a;对于线性时不变&#xff08;LTI&#xff09;系统&#xff0c;H∞范数通常定义为系统频率响应的最大幅值。换句话说&#xff0c;它是系统传递函数在复平面单位圆上…

网络编程:服务器模型-并发服务器-多进程

并发服务器概念&#xff1a; 并发服务器同一时刻可以处理多个客户机的请求 设计思路&#xff1a; 并发服务器是在循环服务器基础上优化过来的 &#xff08;1&#xff09;每连接一个客户机&#xff0c;服务器立马创建子进程或者子线程来跟新的客户机通信 &#xff08;accept之后…

文件操作IO网络编程网络原理

​ 文件操作—IO 文件在计算机中可以代表很多东西 在操作系统中, 文件主要是指硬盘文件 硬盘主要分为机械硬盘和固态硬盘。机械硬盘通过磁头在旋转的磁盘上读取数据&#xff0c;适合顺序读取。而固态硬盘则使用闪存芯片来存储数据&#xff0c;没有机械部件&#xff0c;因此读…

【面试经典题】环形链表

个人主页&#xff1a;一代… 个人专栏&#xff1a;数据结构 在面试中我们经常会遇到有关链表的相关题目&#xff0c;面试官通常会对题目给出拓展 下面我就两个leetcode上的一个双指针的题目为例&#xff0c;并对其进行拓展 题目链接&#xff1a;环形链表 题目描述&#xf…