C++中substr()函数详解
C++ 中 substr
函数详解
substr
是 C++ 标准库中 std::string
类的成员函数,用于从字符串中提取子串。它是字符串处理中常用的工具,掌握其用法能高效处理字符串截取需求。
函数原型
std::string
提供了一种重载形式的 substr
函数:
函数原型 | 说明 |
---|---|
string substr(size_t pos = 0, size_t count = npos) const; | 从字符串中提取子串,返回新的 std::string 对象 |
参数说明
参数 | 类型 | 含义 | 注意事项 |
---|---|---|---|
pos | size_t (无符号整数) | 子串的起始位置(从 0 开始计数的索引) | - 若 pos 超过字符串长度,会抛出 out_of_range 异常- 若 pos 等于字符串长度,返回空字符串 |
count | size_t (无符号整数) | 要提取的字符数量(可选参数) | - 默认值为 npos (一个特殊常量,表示“直到字符串末尾”)- 若 pos + count 超过字符串长度,自动截断到字符串末尾 |
返回值
返回一个新的 std::string
对象,包含从原字符串中提取的子串(原字符串不会被修改)。
示例代码
以下示例展示了 substr
的常见用法:
#include <iostream>
#include <string>using namespace std;int main() {string str = "C++ is fun!";cout << "原字符串:" << str << endl; // 输出:C++ is fun!// 1. 只指定起始位置(提取从 pos 到末尾的所有字符)string sub1 = str.substr(5); cout << "substr(5):" << sub1 << endl; // 输出:is fun!(从索引5开始)// 2. 指定起始位置和提取长度string sub2 = str.substr(0, 3); cout << "substr(0, 3):" << sub2 << endl; // 输出:C++(从索引0开始,提取3个字符)// 3. 提取长度超过剩余字符(自动截断)string sub3 = str.substr(5, 20); cout << "substr(5, 20):" << sub3 << endl; // 输出:is fun!(剩余字符不足20个)// 4. 提取整个字符串(等效于复制)string sub4 = str.substr(0); cout << "substr(0):" << sub4 << endl; // 输出:C++ is fun!// 5. 起始位置等于字符串长度(返回空字符串)string sub5 = str.substr(str.size()); cout << "substr(str.size()) 长度:" << sub5.size() << endl; // 输出:0return 0;
}
注意事项
注意点 | 说明 |
---|---|
索引合法性 | 必须保证 pos <= str.size() ,否则会抛出 out_of_range 异常。建议使用前检查:if (pos <= str.size()) { ... } |
无符号类型陷阱 | pos 和 count 是 size_t (无符号类型),若用负数赋值会导致异常(例如 substr(-1) 会编译错误或运行崩溃)。 |
性能影响 | substr 会创建新字符串,频繁调用可能影响性能(尤其是长字符串)。 |
与 substr 类似的函数 | C 语言中的 strncpy 也可截取字符串,但 substr 更安全(自动处理边界)。 |