新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c++中substr()函数怎样使用,c++substring函数用法

发布时间:2023-09-18 08:52:22

c++中substr()函数怎样使用

在C++中,`substr()`函数用于从字符串中提取子字符串。它接受两个参数:起始位置和子字符串的长度。
下面是`substr()`函数的使用示例:
```cpp
#include
#include
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"。