split函数的c++
时间: 2023-06-23 22:58:57 浏览: 48
在 C++ 中,可以使用 `std::string` 类的 `substr()` 和 `find()` 函数来实现类似于 `split()` 函数的功能。以下是一个示例实现:
```c++
#include <iostream>
#include <vector>
#include <string>
std::vector<std::string> split(std::string str, char delimiter) {
std::vector<std::string> tokens;
size_t pos = 0;
std::string token;
while ((pos = str.find(delimiter)) != std::string::npos) {
token = str.substr(0, pos);
tokens.push_back(token);
str.erase(0, pos + 1);
}
tokens.push_back(str);
return tokens;
}
int main() {
std::string str = "hello,world,how,are,you";
std::vector<std::string> tokens = split(str, ',');
for (std::string token : tokens) {
std::cout << token << std::endl;
}
return 0;
}
```
上述代码将字符串 `str` 按照逗号分隔符切分成多个子字符串,并存储在一个 `std::vector<std::string>` 容器中。可以根据需要修改分隔符字符来适配不同的场景。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)