【C++笔记】STL详解:string的使用

【C++笔记】STL详解:string的使用

前言:

        本文在介绍STL框架基础上,进一步讲解了迭代器、auto关键字和范围for循环的使用方法,接下来我们将重点探讨string类的常用接口及其应用。

        

一、string类对象的常见构造

       

1.1 空字符串构造函数

        

无参构造函数:string();

        

函数功能:构造一个空字符串,长度为零字符。

        

代码示例:演示构造一个空字符

#include <iostream> #include <string> using namespace std; int main() { string s1; // 调用默认构造函数,构造一个空字符串 cout << "s1: " << s1 << endl; // 输出空内容 cout << "s1.size(): " << s1.size() << endl; // 输出 0 return 0; }

        

打印结果如下所示:

        

        

1.2 C 字符串构造函数

        

构造函数原型: string(const char* s)

        

函数功能:通过C风格字符串(const char*)构造string 对象

        

代码示例:演示通过C风格字符串进行构造

#include <iostream> #include <string> using namespace std; int main() { string s2("Hello world"); //通过C类型字符进行构造 cout <<"s2:" << s2 << endl; return 0; }

          

打印结果如下所示:

        

        

1.3 n个字符构造函数

        

构造函数原型:string(size_t n, char c)

        

函数功能:用n个字符c进行构造

        

代码示例:用n个字符‘x’进行构造

#include <iostream> #include <string> using namespace std; int main() { string s3(5,'x'); //通过n个字符进行构造 cout <<"s3:" << s3 << endl; return 0; }

        

打印结果如下所示:

        

1.4 拷贝构造函数

        

构造函数原型: string(const string&s)

        

函数功能:通过拷贝字符串进行构造

        

代码示例:调用拷贝构造函数进行构造str对象

#include <iostream> #include <string> using namespace std; int main() { string original = "Hello C++"; string str(original); // 调用拷贝构造函数 cout << "str: " << str << endl; // 输出 "Hello C++" return 0; }

        

打印结果如下:

               

        

二、string类的容量操作

        

2.1 size

        

size函数        

        

函数原型: size_t size() const;

        

函数功能:返回字符串的长度,以字节为单位。

        

代码示例:演示返回字符串的长度

#include <iostream> #include <string> using namespace std; int main() { string s = "Hello World"; cout << "s.size(): " << s.size() << endl; // 输出 11 return 0; }

        

打印结果如下所示:

        

        

2.2 capacity

        

capacity函数        

        

函数原型: size_t capacity() const;

        

函数功能:返回当前为字符串分配的存储空间的大小,以字节为单位。

        

代码示例:演示返回字符串的空间大小

#include<iostream> #include<string> using namespace std; int main() { string s1("Hello World"); cout <<"s1.capacity():" << s1.capacity() << endl; return 0; }

        

打印结果如下所示:

        

        

2.3 empty

        

empty函数         

        

函数原型:bool empty() const;

        

函数功能:检查字符串是否为空。

                

代码示例:演示字符串是否为空的函数

#include <iostream> #include <string> using namespace std; int main() { string s1 = "hello world"; string s2; cout << "s1.empty(): " << s1.empty() << endl; // 输出 0(false) cout << "s2.empty(): " << s2.empty() << endl; // 输出 1(true) return 0; }

        

打印结果如下所示:

        

        

2.4 clear

        

clear函数        

        

函数原型:void clear();

        

函数功能:删除字符串的内容,使其变为一个空字符串(长度为 0 个字符)。

        

代码示例:清空字符s

#include <iostream> #include <string> using namespace std; int main() { string s = "Hello World"; s.clear(); cout << "After clear, s: " << s << endl; // 输出空 cout << "s.size(): " << s.size() << endl; // 输出 0 cout << "s.capacity(): " << s.capacity() << endl; // 容量可能不变 return 0; }

        

打印结果如下图所示:

        

        

2.5  reserve

        

 reserve 函数       

        

函数原型:  void reserve (size_t n = 0);

        

函数功能:  请求将字符串容量调整为计划中的大小变化,最多为 n 个字符。

        

①如果 n 大于当前字符串容量,该函数将使容器将其容量增加到 n 个字符(或更多)。

        

②在其他所有情况下,它被视为一个非约束性的请求来缩小字符串容量:容器实现可以自由优化,并保留字符串的容量大于 n。

        

注:不同编译器(如 GCC, Clang, MSVC)的初始容量和扩容策略可能略有不同,但核心逻辑一致。

        

代码示例演示:展示扩容函数的使用

#include <iostream> #include <string> using namespace std; // 引入标准命名空间 int main() { string str1; string str2; cout << "=== 不使用 reserve ===" << endl; cout << "初始 str1 容量: " << str1.capacity() << ", 长度: " << str1.length() << endl; // 假设我们要存入一段较长的文本 str1 = "This is a demonstration of the string reserve function in C++."; cout << "赋值后 str1 容量: " << str1.capacity() << ", 长度: " << str1.length() << endl; cout << "\n=== 使用 reserve ===" << endl; cout << "初始 str2 容量: " << str2.capacity() << ", 长度: " << str2.length() << endl; // 预先分配至少 100 个字符的内存 str2.reserve(100); cout << "reserve(100) 后,str2 容量: " << str2.capacity() << ", 长度: " << str2.length() << endl; // 存入同样的文本 str2 = "This is a demonstration of the string reserve function in C++."; cout << "赋值后 str2 容量: " << str2.capacity() << ", 长度: " << str2.length() << endl; return 0; }

        

打印结果如下图所示:

        

        

2.6 resize

        

resize函数        

        

函数原型:



①void resize (size_t n);



②void resize (size_t n, char c);


        

函数功能:将字符串调整为 n 个字符的长度。

        

A.如果 n 小于当前字符串长度,当前值将被缩短到其前 n 个字符,删除第 n 个字符之后的部分。

        

B.如果 n 大于当前字符串长度,当前内容将被扩展,在末尾插入所需数量的字符以达到 n 的长度。如果指定了 c,新元素将被初始化为 c 的副本,否则,它们将被值初始化的字符(空字符)。

        

代码演示:resize的功能

#include <iostream> #include <string> using namespace std; int main() { string s = "Hello C"; s.resize(9, '+'); // 扩展至9个字符,不足部分用'+'填充 cout << "s: " << s << endl; // 输出 "Helloxxx" cout << "s.size():" << s.size() << endl; s.resize(5); // 截断至5字符 cout << "s: " << s << endl; // 输出 "Hello" cout << "s.size(): " << s.size() << endl; return 0; }

        

打印结果如下图所示:

        

        

三、 string类的访问及遍历操作

        

3.1 operator[]          

        

操作符重载   operator[]     

        

函数原型 : 



①char& operator[] (size_t pos);

        

②const char& operator[] (size_t pos) const;


        

函数功能:返回字符串中位置为 pos 的字符的引用。

        

代码演示:通过下标访问字符

#include <iostream> #include <string> using namespace std; int main() { string s2("hello world"); //1. 下标+[] 进行访问元素 cout << "下标访问元素:"; for (int i = 0; i < s2.size(); i++) { cout << s2[i] << " "; } s2[0] = 'H'; cout << "\n" << "更改后下标位置2处的字符串:"; for (int i = 0; i < s2.size(); i++) { cout << s2[i] << " "; } return 0; }

        

打印结果如下所示:

        

        

3.2 迭代器获取:begin 和 end

        

正向迭代器        

        

函数原型:

        

① iterator begin();

        

② iterator end();


        

函数功能:

       

① iterator begin(): 返回一个指向字符串第一个字符的迭代器。

        

② iterator end(): 返回一个指向字符串末尾之后字符的迭代器。

#include <iostream> #include <string> using namespace std; int main() { string s2("hello world"); cout << "迭代器访问元素:"; string::iterator it = s2.begin(); while (it != s2.end()) { cout << *it << " "; ++it; } cout << "\n利用迭代器更改元素:"; it = s2.begin(); while (it != s2.end()) { *it += 2; cout << *it << " "; ++it; } return 0; }

        

打印结果如下所示:

        

        

3.3 范围for循环

        

代码示例:通过范围for进行遍历字符串

#include <iostream> #include <string> using namespace std; int main() { string s2("hello world"); //范围for的使用场景主要应用于: 容器 和 数组 cout << "范围for循环访问元素:"; for (auto& ch : s2) { cout << ch << " "; } cout << "\n范围for循环更改元素:"; for (auto& ch : s2) { ch += 2; cout << ch << " "; } return 0; }

        

打印结果如下所示:

        

        

四、string类的修改操作

                

4.1 push_back      

        

push_back 函数 

        

函数原型:void push_back (char c);

        

函数功能 :将字符 c 附加到字符串末尾,使其长度增加一个。   
           

        

代码示例:演示向字符串中尾插单个字符

#include <iostream> #include <string> using namespace std; int main() { string s("hello world"); cout << "尾插前的s:" << s << endl; // push_back 函数只能尾插单个字符 s.push_back(' '); s.push_back('s'); cout << "push_back尾插字符后的s:" << s << endl; return 0; } 

        

打印结果如下所示:

4.2 operator+= 和 append

        

1.  +=操作符重载(常用)

        

函数原型:

        

① string& operator+= (const string& str);

     

② string& operator+= (const char* s);

         

③  string& operator+= (char c);

        

函数功能:通过在当前值的末尾追加额外的字符来扩展字符串:

        

代码示例:演示+=运算符重载,尾插单个字符,C类型字符串,string类型字符串

#include <iostream> #include <string> using namespace std; int main() { string s("hello world"); cout << "尾插前的s:" << s << endl; // += 运算符重载 s += 'x'; cout << "尾插单个字符的s:" << s << endl; s += " Welcome"; cout << "尾插C类型字符串后的s:" << s << endl; string s2(" Hello C++"); s += s2; cout << "尾插字符串s2后的s:" << s << endl; return 0; }

        

打印结果如下所示:

        

        

2. append函数(不常用)        

        

函数原型:string& append (const string& str);

        

函数功能:通过在当前值的末尾追加附加字符来扩展字符串。   
   

        

代码示例:通过append函数扩展字符串

#include <iostream> #include <string> using namespace std; int main() { string s("Hello world"); cout << "尾插前的s:" << s << endl; //append 函数尾插字符串 s.append(" Welcome C++"); cout << "append尾插字符串后的s:" << s << endl; return 0; } 

        

                

        

4.3 c_str

        

c_str 函数

        

函数原型: const char* c_str() const;

               

函数功能: 返回一个指向包含空字符终止序列的字符数组(即 C 字符串)的指针,该数组表示字符串对象的当前值。

        

代码示例:获取C风格字符串

#include <iostream> #include <string> #include <cstring> using namespace std; int main() { string s = "C++"; const char* p = s.c_str(); // 获取C风格字符串指针 cout << "C-string: " << p << endl; // 输出 "C++" cout << "Length via strlen: " << strlen(p) << endl; // 输出 3 return 0; }

        

打印结果如下所示:

        

        

4.4 find

        

find函数

        

函数原型:

        

① size_t find (const string& str, size_t pos = 0) const;

        

②size_t find (char c, size_t pos = 0) const;

  


        

函数功能:

        

① 从pos位置(默认为0) 查找一个字符串

        

②从pos位置(默认为0) 查找一个字符

        

注意:如果没有找到匹配项,该函数返回 string::npos,npos的类型是size_t,其值被认定为是-1。

        

代码示例:演示查找单个字符和单个字符串,以及验证未查找到字符串返回值

#include <iostream> #include <string> using namespace std; int main() { string s("text.cpp.zip"); size_t pos1 = s.find('.'); cout <<"字符串s中 . 的位置为:" << pos1 << endl; size_t pos2 = s.find("cpp"); cout << "字符串s中 cpp 的位置为:" << pos2 << endl; size_t pos3 = s.find("C++"); if (pos3 == string::npos) { cout << "Not find!"<<endl; } return 0; }

        

打印结果如下所示:

        

        

4.5 substr

        

substr函数        

        

函数原型:string substr (size_t pos = 0, size_t len = npos) const;

        

函数功能:返回一个新构建的string对象,其值初始化为对此对象的一个子字符串的副本。

        

代码示例:演示截取字符串

#include <iostream> #include <string> using namespace std; int main() { string str = "We think in generalities, but we live in details."; string str2 = str.substr(3, 5); // "think" cout << "截取得到下标从3开始之后的五个字符:" << str2 << endl; size_t pos = str.find("live"); // position of "live" in str string str3 = str.substr(pos); // get from "live" to the end cout <<"截取pos位置之后的字符串:" << str3 << '\n'; return 0; }

       

打印结果如下所示:

        

        

4.6 insert

        

insert函数        

        

函数原型:

        

①string& insert (size_t pos, const string& str);

        

②string& insert (size_t pos, const char* s);


       

③string& insert (size_t pos, size_t n, char c);

        

函数功能:在 pos 指定的字符右侧插入额外的字符:

        

代码示例:

#include <iostream> #include <string> using namespace std; int main() { string s("hello world"); cout << "尾插前的s:" << s << endl; // insert函数 插入C类型字符串 s.insert(0, " Byte "); cout << "insert在下标0处插入字符串后的s:" << s << endl; //insert函数 插入string类型字符串 string s2(" Welcome to C++"); size_t pos = s.size(); s.insert(pos, s2); cout << "insert在下标pos处插入字符串后的s:" << s<< endl; //insert插入单个字符需要指定字符个数 s.insert(0, 5, '6'); cout << "insert在下标0处插入5个字符串后的s:" << s << endl; return 0; } 

        

打印结果如下所示:

        

        

4.7 erase

        

erase函数        

        

函数原型:string& erase (size_t pos = 0, size_t len = npos);

        

函数功能:删除字符串的一部分,缩短其长度:

        

代码示例:

#include <iostream> #include <string> using namespace std; // 引入标准命名空间 int main() { string str("This is an example sentence."); cout << str << '\n'; // 初始输出: "This is an example sentence." // 用法 :erase(pos, len) // 从索引 10 开始,删除 8 个字符 (" example") str.erase(10, 8); cout << str << '\n'; // 当前结果: "This is an sentence." return 0; }

        

打印结果如下所示:

                

        

五、string类的非成员函数

        

5.1 operator+

        

operator+ 操作符重载

        

函数原型:

        

①string operator+ (const string& lhs, const string& rhs);

        

②string operator+ (const string& lhs, const char* rhs);

        

③string operator+ (const char* lhs, const string& rhs);

        

函数功能:返回一个新构造的字符串对象,其值为 lhs 中的字符后跟 rhs 中的字符的组合。

                

代码示例:

#include <iostream> #include <string> using namespace std; int main() { string firstlevel("com"); string secondlevel("cplusplus"); string scheme("http://"); string hostname; string url; // 演示 1:string 与 C风格字符串 ("www.")、字符 ('.') 以及其它 string 拼接 hostname = "www." + secondlevel + '.' + firstlevel; // 演示 2:两个 string 对象直接拼接 url = scheme + hostname; cout << url << '\n'; // 预期输出: http://www.cplusplus.com return 0; }

        

打印结果如下所示:

        

        

5.2 operator>> 和 operator<<        

        

operator>> 和 operator<<(输入/输出运算符重载)

        

函数原型:

        

① istream& operator>> (istream& is, string& str);



② ostream& operator<< (ostream& os, const string& str);

        

        

函数功能:



A.   operator>> :从流中读取数据到 string,默认以空格/换行分隔

        

B.   将符合 str 值的字符序列插入到 os 中。

        

代码示例:

#include <iostream> #include <string> using namespace std; int main() { string s; // 输入示例(遇到空格/换行停止) cout << "Enter a word: "; cin >> s; // 输入 "Hello World" cout << "You entered: " << s << endl; // 输出 "Hello"(空格截断) // 输出示例 string name = "Alice"; cout << "Name: " << name << endl; // 输出 "Name: Alice" return 0; } 

        

        

5.3 getline

                

getline函数

        

函数原型:

        

①istream& getline (istream& is, string& str, char delim);

        

②istream& getline (istream& is, string& str);

        

函数功能:从输入流中读取一行(默认以 \n 结尾),可指定分隔符,不会因为' '而中断。

        

代码示例:

#include <iostream> #include <string> using namespace std; int main() { string line; cout << "Enter a line: "; getline(cin, line); // 读取整行(包括空格) cout << "Line: " << line << endl; // 输出完整输入 // 指定分隔符(默认'\n') getline(cin, line, ';'); // 读取直到遇到分号 cout << "Until ';': " << line << endl; return 0; } 

        

5.4 字符串大小比较      

        

代码示例:按照字典序进行比较

        

#include <iostream> #include <string> using namespace std; int main() { string foo = "alpha"; string bar = "beta"; if (foo == bar) cout << "foo and bar are equal\n"; if (foo != bar) cout << "foo and bar are not equal\n"; if (foo < bar) cout << "foo is less than bar\n"; if (foo > bar) cout << "foo is greater than bar\n"; if (foo <= bar) cout << "foo is less than or equal to bar\n"; if (foo >= bar) cout << "foo is greater than or equal to bar\n"; return 0; }

        

打印结果如下所示:

        

        

既然看到这里了,不妨关注+点赞+收藏,感谢大家,若有问题请指正。

        

Read more

Mac mini搭建OpenClaw网关教程,最省心的家庭AI服务器

Mac mini搭建OpenClaw网关教程,最省心的家庭AI服务器

Mac mini搭建OpenClaw网关教程,最省心的家庭AI服务器 前言 对于苹果生态用户来说,Mac mini是搭建家庭AI服务器的最佳选择。M1/M2芯片的Mac mini拥有出色的性能功耗比,配合macOS的稳定性和易用性,让OpenClaw的部署变得前所未有的简单。本文将详细介绍如何在Mac mini上部署OpenClaw,打造最省心的家庭AI网关。 这台设备为什么适合跑 OpenClaw 优点 Apple芯片的卓越性能 M1/M2芯片采用ARM架构,拥有惊人的能效比。M1芯片的8核CPU + 8核GPU配置,在OpenClaw的AI推理任务中表现优异。相比同等功耗的x86处理器,Apple芯片的性能提升明显,同时功耗更低。实测M1 Mac mini在处理复杂AI任务时,功耗仅为15-20W,性能却超过许多桌面级处理器。 macOS的极致稳定性 macOS以稳定著称,系统更新频率适中,不会像Windows那样频繁重启。OpenClaw在macOS上可以长期稳定运行,无需担心系统更新导致服务中断。macOS的Unix内核也为OpenClaw提供了良好的兼容性,所

By Ne0inhk
如何利用AI Coding提效?从工具到思维的全面升级

如何利用AI Coding提效?从工具到思维的全面升级

目录 前言 🔍 一、行业趋势:AI Coding 是"选择题"还是"必答题"? 📊 数据揭示:AI 正在改变开发生态 🌐 行业视角:AI Coding 的演进路径 💡 二、行业专家洞见:AI Coding 实战经验分享 🎤 1. 韦体东:深信服研发主管、开源AI编程产品负责人 🎤 2. 王路敏:极猫科技创始人、技术负责人 🎤 3. 鲲志:脉脉AI创作者、阿里云专家博主 🛠️ 三、工具实战:如何让 AI 真正"提效"? 1️⃣ 场景聚焦:让 AI

By Ne0inhk
OpenClaw WebSocket Channel开发实战:从零打造自定义 AI 通信通道

OpenClaw WebSocket Channel开发实战:从零打造自定义 AI 通信通道

🎯 项目背景 为什么做这个项目? 最近 OpenClaw 特别火🔥,这是一个强大的个人 AI 助手网关,支持接入 WhatsApp、Telegram、Discord 等 15+ 个消息平台。作为一个技术爱好者,我决定深入学习一下它的架构设计。 学习目标: * ✅ 理解多通道 AI 网关的架构模式 * ✅ 掌握 OpenClaw 插件化开发技能 * ✅ 实践 WebSocket 实时双向通信 * ✅ 为社区贡献一个实用的教学案例 项目定位:这不是一个生产级项目,而是一个学习性质的教学案例,帮助其他开发者快速上手 OpenClaw 插件开发。 技术栈 前端层:Vue 3 + WebSocket ↓ 服务端:Python + aiohttp + uv ↓ 通道层:Node.js + ws + OpenClaw Plugin SDK

By Ne0inhk
PyTorch生成式人工智能(5)——分类任务详解

PyTorch生成式人工智能(5)——分类任务详解

PyTorch生成式人工智能(5)——分类任务详解 * 0. 前言 * 1. 使用 PyTorch 进行端到端的深度学习 * 1.1 PyTorch 深度神经网络训练流程 * 1.2 数据预处理 * 2. 二分类 * 2.1 创建数据批次 * 2.2 模型构建与训练 * 2.3 模型测试 * 3. 多类别分类 * 3.1 验证集和提前停止 * 3.2 模型构建与训练 * 小结 * 系列链接 0. 前言 在本节中,我们将介绍神经网络的基本概念,包括损失函数、激活函数、优化器和学习率,这些对于构建和训练深度神经网络至关重要,如果想要深入理解这些知识,推荐通过《PyTorch深度学习实战》了解所需的基本技能和概念,包括多种人工神经网络的架构和训练。

By Ne0inhk