labmat labmat - 21 days ago 6
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

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];
}