labmat labmat - 1 year ago 73
C++ Question

How to concatenate strings by alternating chars from both strings in C++?

Suppose I've the following code

std::string st1 = "ab";
std::string st2 = "xyz";

I want to concatenate these strings by alternating chars so that the output is

std::string output = "axbyz";

How can I do this in C++?

I could concatenate using '+'.

Answer Source

The output shall alternate the characters of each string:

std::string res = "";
for(int i = 0; i < std::max(a.size(), b.size()); i++){
    if (i < a.size())
       res += a[i];
    if (i < b.size())
       res += b[i];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download