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

本文主要是介绍【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更多的内容,感谢大家的支持。♥

这篇关于【C++】string类的使用④(字符串操作String operations || 常量成员Member constants)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/986952

相关文章

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

oracle DBMS_SQL.PARSE的使用方法和示例

《oracleDBMS_SQL.PARSE的使用方法和示例》DBMS_SQL是Oracle数据库中的一个强大包,用于动态构建和执行SQL语句,DBMS_SQL.PARSE过程解析SQL语句或PL/S... 目录语法示例注意事项DBMS_SQL 是 oracle 数据库中的一个强大包,它允许动态地构建和执行

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

Python itertools中accumulate函数用法及使用运用详细讲解

《Pythonitertools中accumulate函数用法及使用运用详细讲解》:本文主要介绍Python的itertools库中的accumulate函数,该函数可以计算累积和或通过指定函数... 目录1.1前言:1.2定义:1.3衍生用法:1.3Leetcode的实际运用:总结 1.1前言:本文将详

浅析如何使用Swagger生成带权限控制的API文档

《浅析如何使用Swagger生成带权限控制的API文档》当涉及到权限控制时,如何生成既安全又详细的API文档就成了一个关键问题,所以这篇文章小编就来和大家好好聊聊如何用Swagger来生成带有... 目录准备工作配置 Swagger权限控制给 API 加上权限注解查看文档注意事项在咱们的开发工作里,API

Java数字转换工具类NumberUtil的使用

《Java数字转换工具类NumberUtil的使用》NumberUtil是一个功能强大的Java工具类,用于处理数字的各种操作,包括数值运算、格式化、随机数生成和数值判断,下面就来介绍一下Number... 目录一、NumberUtil类概述二、主要功能介绍1. 数值运算2. 格式化3. 数值判断4. 随机

Spring排序机制之接口与注解的使用方法

《Spring排序机制之接口与注解的使用方法》本文介绍了Spring中多种排序机制,包括Ordered接口、PriorityOrdered接口、@Order注解和@Priority注解,提供了详细示例... 目录一、Spring 排序的需求场景二、Spring 中的排序机制1、Ordered 接口2、Pri

Springboot 中使用Sentinel的详细步骤

《Springboot中使用Sentinel的详细步骤》文章介绍了如何在SpringBoot中使用Sentinel进行限流和熔断降级,首先添加依赖,配置Sentinel控制台地址,定义受保护的资源,... 目录步骤 1: 添加 Sentinel 依赖步骤 2: 配置 Sentinel步骤 3: 定义受保护的