Separate a string at all occurrences of a delimiter, returning the strings between the delimiters in a container.
The result has at least one element. If the delimiter is not present in the text, the whole text is returned. If there are consecutive delimiters, the collected string between them is the empty string. If the delimiter is directly at the end of the input, the collected string between the end of the input and the delimiter is again the empty string.
split() is the inverse function of join(). It is guaranteed that join(split(text, del), del) == text
.
std::vector<std::string> parts1 =
split(
" hello world",
" ");
assert(parts1.size() == 3);
assert(parts1[0] == ""s);
assert(parts1[1] == "hello"s);
assert(parts1[2] == "world"s);
std::vector<std::string> parts2 =
split(
"<>",
"<>");
assert(parts2.size() == 2);
assert(parts2[0] == ""s);
assert(parts2[1] == ""s);
This function returns a std::vector<std::string>
by default, but a compatible container for string/string_view types can be specified via a template parameter:
- Template Parameters
-
StringContainer | A container for strings or string_view-like types, e.g. std::vector<std::string> or std::list<gul14::string_view> |
ContainerInsertFct | Type for the insert_fct function parameter. |
- Parameters
-
text | The string to be split |
delimiter | The delimiting substring |
insert_fct | By default, split() calls the emplace_back() member function on the container to insert strings. This parameter may contain a different function pointer or object with the signature void f(StringContainer&, gul14::string_view) that is called instead. This can be useful for containers that do not provide emplace_back() or for other customizations. |
- Returns
- a container filled with the substrings that were separated by delimiter in the original string.
auto parts1 = split<std::vector<gul14::string_view>>("Hello world", " ");
assert(parts1.size() == 2);
assert(parts1[0] == "Hello");
assert(parts1[1] == "world");
auto parts2 = split<gul14::SmallVector<std::string, 3>>("a--b--c", "--");
assert(parts2.size() == 3);
assert(parts2[0] == "a");
assert(parts2[1] == "b");
assert(parts2[2] == "c");
using WeirdContainer = std::queue<std::string>;
auto parts3 = split<WeirdContainer>("a.b", ".", inserter);
assert(parts3.size() == 2);
assert(parts3.front() == "a");
assert(parts3.back() == "b");
- See also
- split_sv() returns a vector of string_views,
split(const std::string&, const std::regex&) splits at a delimiter described by a regular expression, and
join() can join the vector back into a string.
- Since
- GUL version 2.5, the return type of split() can be specified as a template parameter and a custom inserter can be specified (it always returned std::vector<std::string> before).