C++ substr用法

substr是C++ std::string类的一个成员函数,用于从字符串中提取子串。

它有两个参数:起始位置和子串长度。下面是一个简单的例子:

#include 
#include 

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 
#include 

int main() {
    std::string str = "Hello, world!";
    std::string sub = str.substr(7);
    std::cout << sub << "\n"; // 输出 "world!"
}

在上面的代码中,我们使用substr函数从字符串str中提取从第7个字符开始到末尾的子串,并将其存储在字符串sub中。然后我们输出这个子串,得到"world!"。

请注意,如果起始位置或长度超出范围,则会抛出一个异常。

你可能感兴趣的:(C/C++,c++,开发语言)