基于算法竞赛的c++编程(18)string类细节问题

本节是string类细节问题

构造与初始化

std::string有多种构造函数:

cpp 复制代码
std::string s1;                // 默认构造,空字符串
std::string s2("Hello");       // 从C字符串构造
std::string s3(s2);            // 拷贝构造
std::string s4(5, 'a');        // 填充构造,结果为"aaaaa"
std::string s5(s2, 1, 3);      // 子串构造,从索引1开始取3个字符,结果为"ell"

访问字符

可用[]at()访问字符:

cpp 复制代码
std::string s = "Hello";
char c1 = s[1];      // 'e',不检查边界
char c2 = s.at(1);   // 'e',抛出std::out_of_range异常

修改操作

追加、插入、删除等操作:

cpp 复制代码
s += " World";       // 追加,s变为"Hello World"
s.append("!");       // 追加,s变为"Hello World!"
s.insert(5, ",");    // 插入,s变为"Hello, World!"
s.erase(5, 1);       // 删除,s变为"Hello World!"

查找与替换

查找子串或字符:

cpp 复制代码
size_t pos = s.find("World");  // 返回首次出现的位置(6)
if (pos != std::string::npos) {
    s.replace(pos, 5, "C++");  // 替换为"C++",s变为"Hello C++!"
}

容量与大小

cpp 复制代码
s.size();     // 当前字符数(9)
s.empty();    // 是否为空
s.resize(10); // 调整大小,不足时填充'\0'
s.capacity(); // 当前分配的内存容量

字符串比较

直接使用比较运算符:

cpp 复制代码
std::string a = "apple", b = "banana";
if (a < b) { /* ... */ }  // 字典序比较

转换与C字符串

转换为C风格字符串:

cpp 复制代码
const char* cstr = s.c_str();  // 返回const char*
char* buf = new char[s.size() + 1];
s.copy(buf, s.size());         // 拷贝到缓冲区

迭代器支持

支持STL迭代器:

cpp 复制代码
for (auto it = s.begin(); it != s.end(); ++it) {
    std::cout << *it;
}
for (char ch : s) { /* ... */ }  // 范围for循环

注意:std::string管理的内存是动态分配的,无需手动释放。C++17后新增了std::string_view用于非占有式字符串视图。

相关推荐
Funny_AI_LAB1 小时前
李飞飞联合杨立昆发表最新论文:超感知AI模型从视频中“看懂”并“预见”三维世界
人工智能·算法·语言模型·音视频
RTC老炮4 小时前
webrtc降噪-PriorSignalModelEstimator类源码分析与算法原理
算法·webrtc
深思慎考4 小时前
微服务即时通讯系统(服务端)——用户子服务实现逻辑全解析(4)
linux·c++·微服务·云原生·架构·通讯系统·大学生项目
一晌小贪欢4 小时前
【Python数据分析】数据分析与可视化
开发语言·python·数据分析·数据可视化·数据清洗
草莓火锅6 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
j_xxx404_6 小时前
C++ STL:阅读list源码|list类模拟|优化构造|优化const迭代器|优化迭代器模板|附源码
开发语言·c++
DreamNotOver6 小时前
批量转换论文正文引用为上标
开发语言·论文上标
散峰而望6 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
Kuo-Teng6 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
fie88896 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab