在 C++ 中,substr
是 std::string
类的一个成员函数,用于从一个字符串中提取子字符串。下面将详细介绍它的使用方法、参数、返回值以及示例。
函数原型
substr
函数有两种重载形式:
收起
cpp
// 形式一:从指定位置开始提取指定长度的子字符串
string substr (size_t pos = 0, size_t len = npos) const;
参数解释
pos
:这是一个size_t
类型的参数,表示子字符串开始的位置,其默认值为0
,即从字符串的起始位置开始提取。len
:同样是size_t
类型的参数,代表要提取的子字符串的长度,默认值为std::string::npos
。当使用默认值时,函数会从pos
位置开始提取直到字符串的末尾。
返回值
函数返回一个新的 std::string
对象,该对象包含从原字符串中提取的子字符串。
异常情况
如果 pos
的值大于字符串的长度,函数会抛出 std::out_of_range
异常。
使用示例
示例 1:提取指定位置和长度的子字符串
收起
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 从位置 7 开始提取长度为 5 的子字符串
std::string sub = str.substr(7, 5);
std::cout << "提取的子字符串是: " << sub << std::endl;
return 0;
}
输出结果:
收起
plaintext
提取的子字符串是: World
在这个示例中,我们从字符串 "Hello, World!"
的位置 7
开始提取了长度为 5
的子字符串 "World"
。
示例 2:从指定位置提取到字符串末尾
收起
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 从位置 7 开始提取到字符串末尾
std::string sub = str.substr(7);
std::cout << "提取的子字符串是: " << sub << std::endl;
return 0;
}
输出结果:
收起
plaintext
提取的子字符串是: World!
此示例中,我们只指定了起始位置 7
,没有指定长度,函数默认从该位置提取到字符串的末尾。
示例 3:处理异常情况
收起
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello";
try {
// 尝试从超出字符串长度的位置提取子字符串
std::string sub = str.substr(10);
std::cout << "提取的子字符串是: " << sub << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "发生异常: " << e.what() << std::endl;
}
return 0;
}
输出结果:
收起
plaintext
发生异常: basic_string::substr: __pos (which is 10) > this->size() (which is 5)
在这个示例中,我们尝试从超出字符串长度的位置 10
开始提取子字符串,这会导致 std::out_of_range
异常被抛出,我们通过 try-catch
块捕获并处理了该异常。