基于算法竞赛的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用于非占有式字符串视图。

相关推荐
程序员泡椒18 分钟前
二分查找Go版本实现
数据结构·c++·算法·leetcode·go·二分
小雨下雨的雨18 分钟前
Flutter鸿蒙共赢——墨染算法:柏林噪声与鸿蒙生态中的数字水墨意境
算法·flutter·华为·交互·harmonyos·鸿蒙
瑾修19 分钟前
golang查找cpu过高的函数
开发语言·后端·golang
kkkAloha24 分钟前
JS笔记汇总
开发语言·javascript·笔记
NAGNIP6 小时前
万字长文!回归模型最全讲解!
算法·面试
LawrenceLan7 小时前
Flutter 零基础入门(十一):空安全(Null Safety)基础
开发语言·flutter·dart
知乎的哥廷根数学学派7 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
txinyu的博客7 小时前
解析业务层的key冲突问题
开发语言·c++·分布式
码不停蹄Zzz7 小时前
C语言第1章
c语言·开发语言
行者968 小时前
Flutter跨平台开发在OpenHarmony上的评分组件实现与优化
开发语言·flutter·harmonyos·鸿蒙