Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate a family of string

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)?

like image 348
InsideLoop Avatar asked Aug 25 '17 07:08

InsideLoop


People also ask

How do I concatenate a list of strings?

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.

How do I concatenate multiple strings?

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.

Can I use Concat with group by?

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.


1 Answers

If you have a string_view type, then you can just accept a collection of string_views, 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;
}
like image 56
Caleth Avatar answered Sep 23 '22 18:09

Caleth