当前位置: 首页 > news >正文

c++STL--string类

目录

string 的定义方式

string 的插入

尾插 push_back

指定位置插入 insert

string 的拼接 append

string 的删除

尾删 pop_back

指定位置删除 erase

string 的查找

正向查找 find

反向查找 rfind

string 的比较 compare

string 的替换 replace

string 的交换 swap

string 的大小和容量

string 中元素的访问

[] 运算符

at() 方法(带边界检查)

范围 for

迭代器

string 中运算符的使用

= 赋值

+= 追加

+ 连接(返回新对象)

>> / << 输入输出

关系运算符(按字典序)

迭代器相关函数

正向迭代器

反向迭代器

string 与 C 字符串的转换

C字符串 → string

string → C字符串

提取子字符串

substr()

copy() 复制到字符数组(不自动加 '\0')

getline 读取含空格的整行

默认以换行符分隔

指定分隔符


string 的定义方式

string类提供了多种构造函数,常用形式如下:

构造函数说明
string()构造空字符串
string(const char* s)复制 C 风格字符串s
string(const char* s, size_t n)复制s的前n个字符
string(size_t n, char c)生成nc字符组成的字符串
string(const string& str)拷贝构造
string(const string& str, size_t pos, size_t len = npos)strpos位置开始,复制len个字符

示例:

#include <iostream> #include <string> using namespace std; int main() { string s1; // 空字符串 string s2("Hello C++"); // 复制 "Hello C++" string s3("Hello C++", 5); // 复制前5个字符 -> "Hello" string s4(8, '*'); // 8个 '*' -> "********" string s5(s2); // 拷贝 s2 string s6(s2, 6, 3); // 从索引6开始复制3个字符 -> "C++" cout << s1 << endl; // (空) cout << s2 << endl; // Hello C++ cout << s3 << endl; // Hello cout << s4 << endl; // ******** cout << s5 << endl; // Hello C++ cout << s6 << endl; // C++ return 0; }

string 的插入

尾插push_back

string s; s.push_back('A'); s.push_back('B'); s.push_back('C'); cout << s << endl; // ABC

指定位置插入insert

string s("Data"); s.insert(4, "Base"); // "Data" + "Base" -> "DataBase" cout << s << endl; // DataBase string t("Struct"); s.insert(4, t); // "Data" + "Struct" + "Base" -> "DataStructBase" cout << s << endl; // DataStructBase s.insert(s.end(), '!'); // 末尾插入字符 cout << s << endl; // DataStructBase!

string 的拼接append

string s1("C++"); string s2(" Programming"); s1.append(s2); // "C++ Programming" s1.append(" is fun"); // "C++ Programming is fun" s1.append(3, '!'); // "C++ Programming is fun!!!" cout << s1 << endl;

string 的删除

尾删pop_back

string s("Hello!"); s.pop_back(); // "Hello" s.pop_back(); // "Hell" cout << s << endl;

指定位置删除erase

string s("I love Python and C++"); s.erase(7, 6); // 删除 "Python" -> "I love and C++" s.erase(7, 1); // 删除多余空格 -> "I love and C++" s.erase(s.begin(), s.begin()+5); // 删除 "I lov" -> "e and C++" cout << s << endl;

string 的查找

正向查找find

string url("https://en.cppreference.com/w/cpp/string/basic_string"); string sub("cpp"); size_t pos1 = url.find(sub); cout << pos1 << endl; // 8 size_t pos2 = url.find("reference"); cout << pos2 << endl; // 20 size_t pos3 = url.find(':'); cout << pos3 << endl; // 5

反向查找rfind

string text("alpha beta alpha gamma"); string word("alpha"); size_t pos1 = text.rfind(word); cout << pos1 << endl; // 11 size_t pos2 = text.rfind("beta"); cout << pos2 << endl; // 6 size_t pos3 = text.rfind('a'); cout << pos3 << endl; // 13

string 的比较compare

比较规则:

  • 返回0:相等

  • 返回<0:当前字符串小于参数

  • 返回>0:当前字符串大于参数

string s1("apple"); string s2("banana"); cout << s1.compare(s2) << endl; // -1 (apple < banana) // 比较 s1 从索引1开始的3个字符("ppl") 与 s2 cout << s1.compare(1, 3, s2) << endl; // -1 // 比较 s1[0..3]("appl") 与 s2[0..3]("bana") cout << s1.compare(0, 4, s2, 0, 4) << endl; // -1

string 的替换replace

string s("I like Java"); s.replace(7, 4, "C++"); // 将"Java"替换为"C++" -> "I like C++" cout << s << endl; s.replace(10, 1, 3, '!'); // 将最后一个字符替换为三个'!' -> "I like C++!!!" cout << s << endl;

string 的交换swap

string a("Hello"); string b("World"); a.swap(b); // 成员函数交换 cout << a << " " << b << endl; // World Hello swap(a, b); // 非成员函数交换 cout << a << " " << b << endl; // Hello World

string 的大小和容量

函数说明
size()/length()返回有效字符个数
max_size()最大可容纳字符数(平台相关)
capacity()当前分配的存储空间大小
resize(n, c)改变有效字符数为n,多出的用c填充
reserve(n)预留至少n个字符的容量
clear()清空内容
empty()判断是否为空

示例:

string s("C++"); cout << s.size() << " " << s.capacity() << endl; // 3 15 s.resize(10, '-'); cout << s << " " << s.size() << endl; // C++------- 10 s.reserve(50); cout << s.capacity() << endl; // 63 (或更大) s.clear(); cout << s.empty() << endl; // 1

string 中元素的访问

[]运算符

string s("C++11"); for (size_t i = 0; i < s.size(); i++) { s[i] = toupper(s[i]); // 转为大写 } cout << s << endl; // C++11 (注意 '+' 不会变)

at()方法(带边界检查)

string s("STL"); for (size_t i = 0; i < s.size(); i++) { s.at(i) = tolower(s.at(i)); } cout << s << endl; // stl

范围 for

string s("C++"); for (char& ch : s) { ch = ch + 1; // 每个字符 ASCII +1 } cout << s << endl; // D++ (C->D, + -> , 第二个+也变)

迭代器

string s("Hello"); for (auto it = s.begin(); it != s.end(); ++it) { *it = *it + 1; } cout << s << endl; // Ifmmp

string 中运算符的使用

=赋值

string s1, s2("C++"), s3; s1 = s2; // string 赋值 s1 = "Python"; // C 字符串赋值 s1 = 'J'; // 字符赋值

+=追加

string s("Hello"); s += " "; s += "World"; s += '!'; cout << s << endl; // Hello World!

+连接(返回新对象)

string a("C++"), b("11"); string c = a + b; // "C++11" string d = a + " and " + b; // "C++ and 11" string e = "Version " + a; // "Version C++"

>>/<<输入输出

string s; cin >> s; // 遇空白停止 cout << s;

关系运算符(按字典序)

string s1("abc"), s2("abd"); cout << (s1 < s2) << endl; // 1 cout << (s1 == "abc") << endl; // 1

迭代器相关函数

正向迭代器

string s("Forward"); for (auto it = s.begin(); it != s.end(); ++it) { cout << *it; } cout << endl; // Forward

反向迭代器

string s("Reverse"); for (auto rit = s.rbegin(); rit != s.rend(); ++rit) { cout << *rit; } cout << endl; // esreveR

string 与 C 字符串的转换

C字符串 → string

const char* cstr = "Hello C++"; string s(cstr); // 直接构造

string → C字符串

string s("Hello C++"); const char* cstr1 = s.c_str(); // 返回 const char*,以 '\0' 结尾 const char* cstr2 = s.data(); // C++11 后与 c_str() 相同 cout << cstr1 << endl;

提取子字符串

substr()

string full("2025-03-30"); string year = full.substr(0, 4); // "2025" string month = full.substr(5, 2); // "03" string day = full.substr(8); // "30" cout << year << "-" << month << "-" << day << endl;

copy()复制到字符数组(不自动加'\0'

string s("abcdef"); char buffer[10]; size_t len = s.copy(buffer, 3, 2); // 从索引2开始复制3个字符 -> "cde" buffer[len] = '\0'; cout << buffer << endl; // cde

getline读取含空格的整行

默认以换行符分隔

string line; cout << "Enter a sentence: "; getline(cin, line); // 输入 "Hello C++ World" cout << line << endl; // 输出 "Hello C++ World"

指定分隔符

string data; getline(cin, data, ','); // 输入 "apple,banana,orange" cout << data << endl; // 输出 "apple"
http://www.gsyq.cn/news/1443057.html

相关文章:

  • Dify-Helm部署中HTTP 405错误的深度剖析与架构级解决方案
  • 5个核心功能让Zotero文献管理效率翻倍:Zotero Style插件完全指南
  • 解密cross-en-fr-it-roberta-sentence-transformer:从XLMRoberta架构到均值池化的核心原理
  • 论文免费降AI工具vs付费工具怎么选?2026年实测对比指南
  • WindowResizer:3大突破解决Windows窗口尺寸强制调整难题的终极免费工具
  • 猫抓浏览器扩展:智能化网页资源获取与管理解决方案
  • 外夹式超声波流量计源头厂家推荐榜 - 液体流量液位品牌推荐
  • 2026年德国留学服务口碑好机构:五家优选深度解析 - 科技焦点
  • 如何永久保存微信聊天记录?WeChatMsg完整指南帮你轻松备份
  • 揭秘PanoHead:360度全头部3D生成的技术内幕
  • 2026年成都护栏网市场概况与采购趋势 - 速递信息
  • NPU vs GPU性能对决:Granite-34B-Code-Instruct-8K推理速度优化指南
  • 2026年服务好留学中介机构排行:五家优选深度解析 - 科技焦点
  • 2026 年 6 月八大员备考难上岸?选对题库少走弯路 - 速递信息
  • 2026重庆配眼镜推荐,商圈怎么选,5家店哪家离你最近 - 配眼镜新资讯
  • DLSS Swapper:5分钟掌握游戏性能优化终极指南
  • 基于PLC自动门控制系统设计(设计源文件+万字报告+讲解)(支持资料、图片参考_降重降ai)_文章底部可以扫码
  • 目前热门的万向滚珠厂家哪家专业 - GrowthUME
  • Claude-Mem:如何为你的AI编程助手构建持久化记忆系统
  • AnnouncementClassfication实战案例:如何用Python实现公告相关性自动识别
  • 如何永久保存微信聊天记录:免费开源工具完整解决方案
  • LongCat-Next视觉功能完全指南:从图像理解到图像生成的完整教程
  • 免费投票系统哪个好免费好用热门推荐, - 投票小程序
  • Spring AI 提示词模板实战:告别硬编码,实现提示词工程化管理
  • 电商客服外包心得:踩过无数坑后,终于选到适配店铺的客服团队 - 速递信息
  • 完全免费!永久保存微信聊天记录的终极解决方案:WeChatMsg完整指南
  • 告别死记硬背!用Rime小狼毫的联想滤镜,一键输入地址、表情和常用语
  • 深入ZYNQMP启动流程:从Boot ROM到EMMC,一次讲清那些官方文档没细说的‘坑’
  • 别再让FBX模型材质拖后腿了!Unity里三步搞定外部材质替换与复用
  • 基于单片机的自动浇花系统的设计与实现(设计源文件+万字报告+讲解)(支持资料、图片参考_降重降ai)_文章底部可以扫码