substr函数用于提取子串,语法为string substr(size_t pos = 0, size_t len = npos);pos为起始索引,len为长度;若pos越界则抛出异常,否则自动截取到末尾;常用于提取扩展名或去除前缀。

在C++中,substr 是 std::string 类提供的一个成员函数,用于从原字符串中提取指定位置和长度的子串。它使用简单,但参数含义需要清楚理解,避免越界或截取错误。
substr 函数的基本语法
函数原型如下:
string substr(size_t pos = 0, size_t len = npos) const;该函数返回一个新字符串,是原字符串从位置 pos 开始、长度为 len 的子串。
参数详解与图解说明
pos:起始位置(索引),从 0 开始计数。
len:希望截取的字符个数,可省略,若省略则表示从 pos 一直取到末尾。
假设有一个字符串:
std::string str = "Hello, World!";其字符索引如下图所示:
H e l l o , W o r l d ! 0 1 2 3 4 5 6 7 8 9 10 11 12
现在我们通过几个例子来理解参数作用:
- str.substr(0, 5) → 从索引 0 开始取 5 个字符 → "Hello"
- str.substr(7, 5) → 从索引 7 开始取 5 个字符 → "World"
- str.substr(7) → 从索引 7 到末尾 → "World!"
- str.substr(5, 3) → 从索引 5 取 3 个字符 → ", W"
边界情况与注意事项
使用 substr 时需注意以下几点:
- 如果 pos 超过了字符串长度(即 pos >= str.length()),会抛出 std::out_of_range 异常。
- 如果 pos + len 超出字符串末尾,substr 会自动截取到末尾为止,不会报错。
- 如果 len 为 0,返回空字符串。
- 默认参数:pos 默认为 0,len 默认为 npos(表示“直到结尾”)。
例如:
str.substr(13); // pos=13 超出范围(长度为13,最大索引12)→ 抛异常 str.substr(10, 100); // 只能取到末尾,结果是 "d!"实用小技巧
常用于分割字符串或提取关键信息:
- 提取文件扩展名: std::string filename = "example.txt"; std::string ext = filename.substr(filename.rfind('.')); // 得到 ".txt"
- 去掉前缀: std::string url = "https://example.com"; std::string domain = url.substr(8); // 去掉 "https://"
基本上就这些。掌握好起始位置和长度两个参数,就能灵活使用 substr 截取任意子串。注意检查 pos 是否合法,避免运行时异常。










