std::string 是 C++ 标准库中封装动态字符数组、自动管理内存的核心字符串类,支持构造赋值、访问遍历、容量查询、修改操作、查找搜索、子串比较及实用技巧。

std::string 是 C++ 标准库中处理文本最核心的类,封装了动态字符数组,自动管理内存,支持常见字符串操作。它定义在 <string></string> 头文件中,底层基于连续内存(通常为 char 数组),具备值语义(拷贝安全、可直接比较、可作为容器元素)。
支持多种初始化方式:
std::string s; → 空字符串std::string s = "hello"; 或 std::string s("world");
std::string s(5, 'a'); → "aaaaa"std::string s2(s1, pos, len); 或 std::string s2(s1.substr(pos, len));
std::string s(first_it, last_it);
s = "new";、s.assign("abc");、s.assign(3, 'x');、s.assign(it1, it2);
提供安全且高效的元素访问接口:
s[i]:不检查越界(类似数组,快但不安全)s.at(i):带下标检查,越界抛 std::out_of_range
s.front() / s.back():获取首尾字符(非空时有效)s.begin()、s.end()、s.cbegin() 等,支持范围 for 循环:for (char c : s) { ... }
s.data():返回指向内部缓冲区的 const char*(C++11 起保证以 '\0' 结尾,可用作 C 接口输入)用于判断和预分配空间:
立即学习“C++免费学习笔记(深入)”;
s.empty():是否为空(比 s.size() == 0 更清晰高效)s.size() / s.length():字符数(等价,size() 更常用)s.max_size():系统允许的最大长度(极少手动使用)s.capacity():当前已分配内存能容纳的字符数(不一定等于 size)s.reserve(n):预留至少 n 字符空间,避免后续追加时频繁重分配s.shrink_to_fit():请求释放多余容量(C++11,非强制,实现可忽略)增删改查的核心能力:
s += "abc";、s.append("def");、s.push_back('x');
s.insert(pos, "xyz");、s.insert(pos, n, c);、s.insert(it, c);
s.erase(pos, len);、s.erase(it);、s.erase(first, last);
s.replace(pos, len, "new");、s.replace(it1, it2, "new");
s.clear();(size 变 0,capacity 不变)s1.swap(s2); 或 std::swap(s1, s2);(常数时间,高效)返回位置索引(size_t 类型),失败时返回 std::string::npos(通常是 -1 的无符号表示):
s.find("sub");:从头正向查找第一次出现位置s.rfind("sub");:从尾反向查找最后一次出现位置s.find_first_of("aeiou");:查找任意一个给定字符首次出现位置s.find_last_of("0123456789");:查找任意一个数字最后一次出现位置s.find_first_not_of(" \t\n");:查找首个非空白字符位置(常用于 trim)s.find_last_not_of(" \t\n");:查找最后一个非空白字符位置提取与判断关系:
s.substr(pos, len);:返回从 pos 开始、最多 len 个字符的新字符串(len 默认到末尾)、!=、、<code>、<code>>、>=(字典序,区分大小写)
s.compare(t);:返回负/0/正,类似 strcmp;也可用 s.compare(pos1, len1, t, pos2, len2); 比较子串一些高频但非成员函数的操作(需配合算法或手动实现):
find_first_not_of 和 find_last_not_of 计算边界后 substr
std::stringstream 或循环调用 find/substr
std::toupper/std::tolower(注意 locale)std::stoi、std::stod 等(在 <string></string> 中声明)掌握这些操作,就能覆盖绝大多数日常字符串处理需求。实际使用中优先考虑安全性(如用 at() 替代 [] 调试期)、效率(合理 reserve)、可读性(运算符重载让代码接近自然语言)。
以上就是C++中的std::string有哪些常用操作?(函数汇总)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号