c++ 截取std::string
时间: 2024-12-20 22:12:57 浏览: 54
在C++中,如果你有一个`std::string`类型的变量并想要截取其中的一部分,可以使用`substr()`函数。这个函数接受两个整数参数:起始位置和终止位置(不包含在内)。下面是一个例子:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
size_t start_pos = 7;
size_t end_pos = 12;
std::string substr = str.substr(start_pos, end_pos - start_pos);
std::cout << "Substring: " << substr << std::endl; // 输出 "World"
return 0;
}
```
在这个例子中,`substr(7, 6)`表示从第8个字符(因为索引是从0开始的)开始,截取5个字符。
如果需要检查子串是否存在于原字符串中,可以先使用`find()`函数获取其位置:
```cpp
size_t pos = str.find("World");
if (pos != std::string::npos) {
std::string substr = str.substr(pos, 6);
std::cout << "Substring found at position " << pos << ": " << substr << std::endl;
} else {
std::cout << "Substring not found." << std::endl;
}
```
这里假设找到就截取,没找到则不截取。
阅读全文
相关推荐


















