c++ split string into char array code example

Example 1: split string on character c++

#include <string>       // std::string
#include <sstream>      // std::stringstream

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);
}
// seglist = {"this", "is", "a", "test", "string"};

Example 2: 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
}

Tags:

Cpp Example