I would like to write a function that concatenates any sequence of std::string
with just one malloc behind the scene. As a consequence, the total length of the string needs to be computed first. The function needs to be used that way:
std::string s0 = ...;
std::string s1 = ...;
std::string s2 = ...;
std::string s = join(s0, s1, s2);
A better join
would use a mix of std::string
and std::string_view
. It would be even better if we could add string literals. How would you write such a function in C++11 (it needs to compile with gcc 4.8.5
and Visual Studio 2015
)?
You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
To concatenate strings in MySQL with GROUP BY, you need to use GROUP_CONCAT() with a SEPARATOR parameter which may be comma(') or space (' ') etc.
If you have a string_view
type, then you can just accept a collection of string_view
s, sum their sizes, allocate, then copy in.
std::string join(std::initializer_list<string_view> values)
{
std::string result;
result.reserve(std::accumulate(values.begin(), values.end(), 0, [](string_view s) { return s.length(); }));
std::for_each(values.begin(), values.end(), [&result](string_view s) { result.append(s.data()); });
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With