给定两个字符串s,t,要求将s中出现的t当作分隔符,将s分割为多个字串

给定两个字符串s,t,要求将s中出现的t当作分隔符,将s分割为多个字串

怎么写呢谢谢帮助

基于Monster 组和GPT的调写:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string> split(string s, string t) {
    vector<string> res;  // 存储分割结果
    int pos = 0;
    while (true) {
        int idx = s.find(t, pos);  // 查找分隔符位置
        if (idx == string::npos) {  // 分隔符不存在
            res.push_back(s.substr(pos));  // 分割剩余部分
            break;
        }
        res.push_back(s.substr(pos, idx - pos));  // 分割子串
        pos = idx + t.size();  // 移动位置
    }
    return res;
}

int main() {
    string s = "hello,world,how,are,you";
    string t = ",";
    vector<string> res = split(s, t);
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << endl;
    }
    return 0;
}


代码中,我们首先定义一个 split 函数,它接受两个参数:要分割的字符串 s 和分隔符 t。在函数中,我们使用 string 类型的成员函数 find 来查找分隔符的位置,然后使用 substr 函数来分割子串。最后,将分割得到的子串存储到 vector 容器中并返回。