Intertwine characters in strings

Basically assignment wants us to mix up the characters in strings. like so ("Fred", "Mary") yields "FyrreadM". And if one string is longer than the other, append the unused characters (in reverse order if the second string is longer).
like so, ("Sue", "Peggy") yields "SyugegeP".

I am kind of stuck on this problem, not sure where to start.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <algorithm>

std::string intertwine( const std::string& first, std::string second )
{
    std::string result ;

    const auto n = std::min( first.size(), second.size() ) ; // common size

    // if the second string is longer, reverse it (note: second is passed by value)
    if( n < second.size() ) second = { second.rbegin(), second.rend() } ;

    // intertwine the common characters from the two strings
    for( std::size_t i = 0 ; i < n ; ++i ) result += { first[i], second[i] } ;

    // append the unused characters of the longer string
    if( n < first.size() ) result += { first.begin()+n, first.end() } ;
    else result += { second.begin()+n, second.end() } ;

    return result ;
}

int main()
{
    std::cout << intertwine( "Fred", "Mary" ) << '\n' // FMraerdy
              << intertwine( "Sue", "Peggy" ) << '\n' // SyugegeP
              << intertwine( "Stroustrup", "Koenig" ) << '\n' ; // SKtoreonuisgtrup
}

http://coliru.stacked-crooked.com/a/09e099b5cad039a3

This would give you an idea about the logic. Now, try writing it on your own.
The problem has two parts:


1. Reverse a string

I wrote a function:

std::string reverse( const std::string& s )

Inside the function I just used the std::reverse() algorithm to reverse a copy of the argument, which I then return.

Of course, you can do it yourself just as easily: start indexing from both ends of the string, swap, increment/decrement the indices, repeat until they cross.


2. Zip two strings together

Consider the unequal strings that you want to interleave:

    Sue
    yggeP

While there are characters remaining in both strings, get the next character from each string and add them to the result string.

Once one (or both) of the strings is out of characters, simply append the characters from the remaining string to the result string.

Sue    Sue    Sue      Sue
yggeP  yggeP  yggeP    yggeP
↑       ↑       ↑         ↑
→Sy    →Syug  →Syugeg  →SyugegeP

Notice how we just use the next two letters.

In the final step, we ran out of letters for one of the names, so we just tacked the remaining letters in the other name onto the end.

You can do this in about fifteen lines of code.

Good luck!
I got it thanks guys!
Topic archived. No new replies allowed.