

新闻资讯
技术学院C++中string常用操作基于std::string成员函数和配合,无需C风格函数或手动内存管理;支持多种构造、查找、截取、替换、遍历及转换操作,全部异常安全且RAII管理。
C++ 中 string 的常用操作其实很直观,核心是掌握标准库 std::string 提供的成员函数和部分 配合用法,不需要额外引入 C 风格字符串处理函数(如 strcpy、strcat 等),也避免手动管理内存。
支持多种构造方式,安全且简洁:
std::string s; → 空字符串std::string s("hello"); 或 std::string s{"world"};
std::string s(5, 'a'); → "aaaaa"std::string s1(s, pos, len); 或 s.substr(pos, len)
快速定位内容或验证状态,返回 std::string::npos 表示未找到:
s.find("ab"):从前往后找首次出现位置s.rfind("ab"):从后往前找最后一次出现位置s.find_first_of("aeiou"):找任意一个元音首次出现位置s.find_first_not_of(" \t\n"):跳过前导空白s.empty()、s.length() / s.size()、s == "abc" 等直接判断所有操作均返回新字符串或就地修改,不破坏原字符串安全性:
s.substr(pos, len):提取子串(越界时自动截断)s.replace(pos, len, "new"):替换指定区间s.insert(pos, "add") 或 s.erase(pos, len)
s.append("end")、s.push_back('x')、s.pop_back()(C++11 起)s.erase(0, s.find_first_not_of(" \t\n\r")); s.erase(s.find_last_not_of(" \t\n\r") + 1);
利用范围 for、迭代器或 STL 算法提升表达力:
for (char c : s) { ... } 或 for (auto it = s.begin(); it != s.end(); ++it)
):std::transform(s.begin(), s.end(), s.begin(), ::toupper);
std:
:stringstream 或 find + substr 循环)std::stoi(s)、std::stod(s)、std::to_string(123)
不复杂但容易忽略:所有成员函数都基于 RAII 和异常安全设计,无需手动释放内存;慎用 c_str() 返回的指针——它只在 string 对象有效且未被修改时有效。