substr是C++ std::string类的一个成员函数,用于从字符串中提取子串。
它有两个参数:起始位置和子串长度。下面是一个简单的例子:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string sub = str.substr(7, 5);
std::cout << sub << "\n"; // 输出 "world"
}
在上面的代码中,我们使用substr函数从字符串str中提取从第7个字符开始,长度为5的子串,并将其存储在字符串sub中。然后我们输出这个子串,得到"world"。
如果省略第二个参数,则默认提取到字符串末尾。例如:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string sub = str.substr(7);
std::cout << sub << "\n"; // 输出 "world!"
}
在上面的代码中,我们使用substr函数从字符串str中提取从第7个字符开始到末尾的子串,并将其存储在字符串sub中。然后我们输出这个子串,得到"world!"。
请注意,如果起始位置或长度超出范围,则会抛出一个异常。
substr是C++std::string类的成员函数,用于从字符串中提取子串。它接受起始位置和长度作为参数,可用来截取指定部分的字符串。如果参数超出范围,会抛出异常。示例代码展示了如何使用substr函数来提取和输出子串。

5168

被折叠的 条评论
为什么被折叠?



