c++ 字符串切割split
时间: 2023-10-18 12:55:26 浏览: 94
C++中可以使用stringstream和getline函数来实现字符串的分割。
具体步骤如下:
1. 将要分割的字符串存入stringstream对象中。
2. 使用getline函数从stringstream对象中读取每个子字符串,并将其存入vector容器中。
3. 遍历vector容器,即可得到分割后的每个子字符串。
示例代码如下:
```c++
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
vector<string> split(string str, char delimiter) {
vector<string> result;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
result.push_back(token);
}
return result;
}
int main() {
string str = "hello,world,how,are,you";
char delimiter = ',';
vector<string> result = split(str, delimiter);
for (auto s : result) {
cout << s << endl;
}
return ;
}
```
输出结果为:
```
hello
world
how
are
you
```
阅读全文
相关推荐

















