C++ std::string Splitting

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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!"


Got any C++ Question?