mercredi 2 septembre 2020

how to split a std::string into a vector with char* element

I want to split a std::string into a char vector. The size for each char after splited is different. Following is my code:

std::vector<char*> split(const std::string& str, const std::string& delim)
{
    std::vector<char*> res;
    if ("" == str) return  res;
    std::string strs = str + delim;
    size_t pos;
    size_t size = strs.size();

    for (int i = 0; i < size; ++i) {
        pos = strs.find(delim, i); 
        if (pos < size) { 
            std::string s = strs.substr(i, pos - i);
            if (s != " " && s != "") 
            {
                char* te;// I can't not assign char te[XX] since I don't know the length yet
                strcpy_s(te, s.c_str());  //there is wrong here
                res.push_back(te);
            }
            i = pos + delim.size() - 1;
        }

    }
    return res;
}


int main()
{
std::string s1="it is a happy day today";
std::string delim1=" ";
std::vector<char*> result_s1=split(s1,delim1);

return 0;
}

I expect to return a vector with element of: "it" "is" "a" "happy" "day" "today", but fail.

Anybody can help? thank you.

Aucun commentaire:

Enregistrer un commentaire