C++ Splitting


Example

Use std::string::substr to split a string. There are two variants of this member function.

The first takes a starting position from which the returned substring should begin. The starting position must be valid in the range (0, str.length()]:

std::string str = "Hello foo, bar and world!";
std::string newstr = str.substr(11); // "bar and world!"

The second takes a starting position and a total length of the new substring. Regardless of the length, the substring will never go past the end of the source string:

std::string str = "Hello foo, bar and world!";
std::string newstr = str.substr(15, 3); // "and"

Note that you can also call substr with no arguments, in this case an exact copy of the string is returned

std::string str = "Hello foo, bar and world!";
std::string newstr = str.substr(); // "Hello foo, bar and world!"