温馨提示×

c++中substr()函数如何使用

c++
小亿
95
2023-09-15 10:20:37
栏目: 编程语言

在C++中,substr()函数用于从字符串中提取子字符串。它接受两个参数:起始位置和子字符串的长度。

下面是substr()函数的使用示例:

#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string sub1 = str.substr(7); // 从索引7开始提取整个字符串
std::cout << sub1 << std::endl;   // 输出: "World!"
std::string sub2 = str.substr(0, 5); // 从索引0开始提取长度为5的子字符串
std::cout << sub2 << std::endl;       // 输出: "Hello"
return 0;
}

在上面的示例中,str.substr(7)提取了从索引7开始的子字符串,即"World!“,而str.substr(0, 5)提取了从索引0开始长度为5的子字符串,即"Hello”。

0