C++中1个string字符串根据指定字符拆成几个字符串

3种实现方式:

int split(char **arr, char *str, const char *delim){
    char *s = strtok(str, delim);
    int c=0;
    while (s!=NULL) {
        *arr++ = s;
        s = strtok(NULL, delim);
        c++;
    }
    return c;
}
 
vector split(char *str, const char *delim) {
    vector elems;
    char *s = strtok(str, delim);
    while (s!=NULL) {
        elems.push_back(s);
        s = strtok(NULL, delim);
    }
    return elems;
}
vector split(const string& s, const string& delim) {
    vector elems;
    size_t pos = 0;
    size_t len = s.length();
    size_t delim_len = delim.length();
    while (pos < len) {
        int find_pos = s.find(delim, pos);
        if (find_pos < 0) {
            elems.push_back(s.substr(pos, len - pos));
            break;
        }
        elems.push_back(s.substr(pos, find_pos - pos));
        pos = find_pos + delim_len;
    }
    return elems;
}

你可能感兴趣的:(C++学习笔记)