Answers for "split a string in c++ stl"

C++
4

c++ split at character

std::stringstream test("this_is_a_test_string");
std::string segment;
std::vector<std::string> seglist;

while(std::getline(test, segment, '_'))
{
   seglist.push_back(segment); //Spit string at '_' character
}
Posted by: Guest on February-26-2020
1

tokenize string c++

//the program take input as string and delimiter is ','.
//delimiter can  be changed in line 9;

std::vector<std::string> tokenise(const std::string &str){
    std::vector<std::string> tokens;
    int first = 0;
    //std::cout<<"aditya";
    while(first<str.size()){
        int second = str.find_first_of(',',first);
        //first has index of start of token
        //second has index of end of token + 1;
        if(second==std::string::npos){
            second = str.size();
        }
        std::string token = str.substr(first, second-first);
        //axaxax,asas,csdcs,cscds
        //0123456
        tokens.push_back(token);
        first = second + 1;
    }
    return tokens;
}
Posted by: Guest on May-08-2020
0

c ++ split_string

std::vector<std::string> split_string(const std::string& str,
                                      const std::string& delimiter)
{
    std::vector<std::string> strings;

    std::string::size_type pos = 0;
    std::string::size_type prev = 0;
    while ((pos = str.find(delimiter, prev)) != std::string::npos)
    {
        strings.push_back(str.substr(prev, pos - prev));
        prev = pos + 1;
    }

    // To get the last substring (or only, if delimiter is not found)
    strings.push_back(str.substr(prev));

    return strings;
}
Posted by: Guest on August-12-2021

Browse Popular Code Answers by Language