如何使用substr函数从字符串中提取指定长度的子字符串?
发布时间:2023-10-08 10:21:10
要使用substr函数从字符串中提取指定长度的子字符串,需要使用函数的两个参数:起始位置和子字符串的长度。
substr函数的语法如下:
str.substr(start, length);
- str:要从中提取子字符串的源字符串。
- start:子字符串的起始位置。索引从0开始,表示从第一个字符开始截取。
- length:要提取的子字符串的长度。如果不指定这个参数,则提取从起始位置到字符串末尾的所有字符。
下面是一个示例,演示如何使用substr函数从字符串中提取指定长度的子字符串:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
string sub = str.substr(7, 5); // 从索引7开始提取5个字符
cout << sub << endl; // 输出 "world"
return 0;
}
在这个示例中,从字符串"Hello, world!"中提取子字符串"world",起始位置为索引7,长度为5。输出结果为"world"。
使用substr函数时需要注意以下几点:
1. 起始位置和长度参数都必须是非负整数。
2. 如果起始位置超出了字符串的范围,substr函数将返回空字符串。
3. 如果起始位置加上长度超过了字符串的长度,substr函数将提取从起始位置到字符串的末尾的字符。
希望以上解答能帮到你!
