新闻详情

新闻详情

首页 / 资讯中心 / 详情

C++小白记:string类用法

发布时间:2026/10/30 9:42:19来源:尧图网络
C++小白记:string类用法
目录1.引言什么是字符串C 风格字符串 vs std::string2. std::string 基础定义与初始化字符串输入与输出3. 字符串操作3.1字符串拼接与连接3.2 比较字符串3.3 查找与替换3.4 子字符串与切片4. 字符串的常用成员函数4.1 长度与容量4.2 访问字符4.3 转换大小写4.4 其他有用的函数5. 高级用法5.1 字符串流stringstream5.2 字符串与其他数据类型的转换结语1.引言什么是字符串字符串是由一系列字符组成的序列用于表示文本信息。它在编程中被广泛应用于用户交互、文件处理、数据解析等场景。C 风格字符串 vsstd::string在 C 中有两种主要的字符串类型C 风格字符串C-strings基于字符数组以空字符 (\0) 结尾。Cstd::string类更高级、功能更丰富的字符串类封装了字符串操作的复杂性。C 风格字符串示例char cstr[] Hello, World!;std::string示例#include string std::string str Hello, World!;2.std::string基础定义与初始化std::string是 C 标准库中的一个类位于string头文件中。它封装了字符序列并提供了丰富的成员函数用于操作字符串。初始化有很多中方式如下图这个只要了解一下就行包含头文件#includestring初始化示例#include iostream #include string int main() { // 默认构造函数 std::string str1; // 使用字符串字面值初始化 std::string str2 Hello; // 使用拷贝构造函数 std::string str3(str2); // 使用部分初始化 std::string str4(str2, 0, 3); // Hel // 使用重复字符初始化 std::string str5(5, a); std::cout str1: str1 std::endl; std::cout str2: str2 std::endl; std::cout str3: str3 std::endl; std::cout str4: str4 std::endl; std::cout str5: str5 std::endl; return 0; }输出字符串输入与输出输出字符串#include iostream #include string int main() { std::string gre Hello, C Strings!; std::cout gre std::endl; return 0; }从用户输入字符串#include iostream #include string int main() { std::string input; std::cout 请输入一个字符串; std::cin input; // 读取直到第一个空白字符 std::cout 您输入的字符串是 input std::endl; return 0; }读取包含空格的整行字符串#include iostream #include string int main() { std::string line; std::cout 请输入一行文本; std::getline(std::cin, line); std::cout 您输入的文本是 line std::endl; return 0; }3. 字符串操作常用的字符串操作如下,了解就行3.1字符串拼接与连接使用运算符#include iostream #include string int main() { std::string first Hello, ; std::string second World!; std::string combined first second; std::cout combined std::endl; // 输出: Hello, World! return 0; }使用append()函数// 字符串追加 std::string strhello; str.append(, world); std::cout str std::endl;使用运算符// 拼接字符串 strdata; str stream; std::cout str std::endl;3.2 比较字符串关于字符串的比较其实是逐个位置按照字符比较计算机中字符存储的方式是ASCII码表每个字符对应一个ASCII码值比较字符就是比较ASCII码值的大小这是我从网上找的表格资料其中一些控制字符也是通过ASCII码存储的还可以使用,!,,,,运算符string aapple; std::string bApple; // 字符串字典序比较 if(a b){ std::cout a is less than b std::endl; }else if (a b){ std::cout a is equal to b std::endl; }else{ std::cout a is greater than b std::endl; }输出3.3 查找与替换使用find()查找子字符串//查找字符串 std::string text The quick brown fox jumps over the lazy dog.; std::string word fox; auto pos text.find(word); // 查找子串 if(pos std::string::npos){ // npos代表未找到 std::cout 未匹配到内容 std::endl; std::cout pos std::endl; }else{ std::cout 匹配位置: pos std::endl; }替换子字符串//替换字符串 text I like cats.; std::string from cats; std::string to dogs; pos text.find(from); if(pos ! std::string::npos){ text.replace(pos,from.length(),to); // 替换指定子串 std::cout 替换后: text std::endl; }else{ std::cout from 未找到std::endl; }3.4 子字符串与切片使用substr()获取子字符串//提取子串 str Hello, World!; std::string sub str.substr(7,5); // 截取起始下标截取长度 std::cout 子串: sub std::endl; std::string new_sub str.substr(7); // 只传起始下标截取到末尾 std::cout 子串: new_sub std::endl;注意如果省略第二个参数substr()会返回从起始位置到字符串末尾的所有字符。4. 字符串的常用成员函数4.1 长度与容量获取字符串长度#include iostream #include string int main() { std::string str C Programming; std::cout 字符串长度: str.length() std::endl; // 输出: 14 // 或者使用 size() std::cout 字符串大小: str.size() std::endl; // 输出: 14 return 0; }获取字符串容量每个std::string对象都有一个容量capacity表示它当前能够持有的最大字符数而不需要重新分配内存。#include iostream #include string int main() { std::string str Hello; std::cout 初始容量: str.capacity() std::endl; str , World!; std::cout 追加后的容量: str.capacity() std::endl; return 0; }输出示例初始容量: 15 追加后的容量: 15注意容量可能因实现而异并不保证它等于长度容量是一个指数级扩充。4.2 访问字符对字符串中的字符操作有如下方法, 切记需包含头文件使用索引访问单个字符#include iostream #include string int main() { std::string str ABCDE; // 正向索引 for (int i 0; i str.length(); i) { std::cout 字符 i : str[i] std::endl; } //反向遍历 for(int i str.length() - 1; i 0 ; i --){ std::cout 下标为 i 的字符为 str[i] std::endl; } return 0; }使用at()函数包含边界检查//try-catch捕获异常 #include iostream #include string int main() { std::string str ABCDE; try { char c str.at(10); // 超出范围会抛出异常 } catch (const std::out_of_range e) { std::cout 异常捕获: e.what() std::endl; } return 0; }4.3 转换大小写C 标准库中的std::toupper和std::tolower可以用于转换字符的大小写。结合std::transform可以实现整个字符串的大小写转换。转换为大写#include iostream #include string #include algorithm #include cctype int main() { std::string str Hello, World!; // 全部转大写 std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){ return std::toupper(c);}); // lambda表达式,接收一个字符c对c进行转大写操作 std::cout str std::endl; // 以小写为例上面的逻辑相当于迭代器遍历全部转小写 for(auto iter str.begin(); iter ! str.end(); iter){ *iter std::tolower(*iter); } std::cout str std::endl; return 0; }4.4 其他有用的函数empty()检查字符串是否为空std::string str; if (str.empty()) { std::cout 字符串为空。 std::endl; }clear()清空字符串内容std::string str Clear me!; str.clear(); std::cout str: str std::endl; // 输出为空erase()删除字符串的部分内容std::string str Hello, World!; str.erase(5, 7); // 从位置5开始删除7个字符 std::cout str std::endl; // 输出: Hello!insert()在指定位置插入字符串或字符std::string str Hello World; str.insert(5, ,); std::cout str std::endl; // 输出: Hello, Worldreplace():替换字符串的部分内容前面已示例。find_first_of(),find_last_of()查找字符集合中的任何一个字符。std::string str apple, banana, cherry; size_t pos str.find_first_of(, ); std::cout 第一个逗号或空格的位置: pos std::endl; // 输出: 55. 高级用法5.1 字符串流stringstreamstd::stringstream是 C 标准库中第sstream头文件提供的一个类用于在内存中进行字符串的读写操作类似于文件流。基本用法示例#include iostream #include sstream #include string int main() { std::stringstream ss; ss Value: 42 , 3.14; std::string result ss.str(); std::cout result std::endl; // 输出: Value: 42, 3.14 return 0; }从字符串流中读取数据// 字符串分割提取数字、字符串 std::string data 123 45.67 Hello; std::stringstream ss1(data); //将字符串存入流中 int a1; double b1; std::string c; ss1 a1 b1 c; std::cout a1: a1 , b1: b1 , c: c std::endl; // 输出: a: 123, b: 45.67, c: Hello5.2 字符串与其他数据类型的转换将其他类型转换为std::string使用 std::to_string():// 数字转字符串 to_string int num 100; double pi 3.14159; str1 std::to_string(num); str2 std::to_string(pi); std::cout str1: str1 , str2: str2 std::endl; // 输出: str1: 100, str2: 3.141590将std::string转换为其他类型使用字符串流#include iostream #include sstream #include string int main() { std::string numStr 256; std::string piStr 3.14; int num; double pi; std::stringstream ss1(numStr); ss1 num; std::stringstream ss2(piStr); ss2 pi; std::cout num: num , pi: pi std::endl; // 输出: num: 256, pi: 3.14 return 0; }使用std::stoi(),std::stod()等函数C11 及以上#include iostream #include string int main() { std::string numStr 256; std::string piStr 3.14; int num std::stoi(numStr); double pi std::stod(piStr); std::cout num: num , pi: pi std::endl; // 输出: num: 256, pi: 3.14 return 0; }这个用法就会简单很多。结语今日任务是学习string类的一些用法Fighting!
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

【外设】之大彩串口显示屏 2026/10/30 4:02:09

【外设】之大彩串口显示屏

大彩串口屏初步使用 1 .官网下载 STM32 屏幕 GUI 设计资料 http://www.gz-dc.com/category/typeid/4112 找到 STM32 Keil 工程,移植相关代码因项目而异进行移植,由于项目简单,本人只对用到的指令接口进行修改。 比如:注意事项&…

阅读更多 →
无法下载Windows系统iso文件 2026/10/29 23:30:48

无法下载Windows系统iso文件

当我遇到这个问题的时候,我打开了一个网站: 登录 然后我打算下载的时候: 突然那个官方的连接就可以下载了:

阅读更多 →
【清华代码熊】DeepSeek V4.1 Flash 后训练详解 2026/10/29 13:36:24

【清华代码熊】DeepSeek V4.1 Flash 后训练详解

📌 上期解析了 DeepSeek V4.1 Flash 模型架构改进,本期解析 DeepSeek V4.1 Flash 预训练/后训练技术: 🌟 预训练:45T 文本 多模态混合语料、直接训练 sparse attention(取消 DeepSeek V4 的 dense 冷启动&…

阅读更多 →
Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ... 2026/10/29 19:55:35

Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ...

文章主要内容和创新点 主要内容 本文聚焦于多模态大语言模型(MLLM)强化学习(RL)训练中的效率问题,提出了一个名为Shuffle-R1的框架。研究发现,当前RL训练存在两个关键缺陷: 优势值坍缩(Advantage Collapsing):批次中大多数优势值集中在零附近,导致有效梯度信号被淹…

阅读更多 →
PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction 2026/10/29 13:36:50

PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction

一、文章主要内容总结 本文聚焦于利用大型语言模型(LLMs)实现个人身份信息(PII)脱敏的研究,旨在解决传统脱敏方法(如基于规则的系统、领域特定命名实体识别(NER)模型)泛化能力差、跨格式/跨语境适应性弱的问题。 研究通过全面评估多种LLM架构(包括密集型LLM(D-LLM…

阅读更多 →
LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model 2026/10/30 5:26:05

LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model

文章主要内容和创新点 主要内容 本文聚焦于二进制图像-文本相关性评估任务(判断图像与文本“相关”或“不相关”),针对该任务中文本格式多样、相关性定义随场景变化等挑战,提出了基于多模态大语言模型(MLLM)的解决方案LLaVA-RE。 模型设计:LLaVA-RE基于LLaVA 1.5架构,…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉