a slightly more efficient method is to also use a reverse-iterator, which starts at the end of the new string and the beginning of the old string.
In each iteration, the following happens:
- The first character of the source string is written to the last character of the target string
- The last character of the source string is written to the first character of the target string
- The forward iterator is increased by one
- The reverse iterator is decreased by one
I can see how this could be confusing to read, so here's a bit of code to show you more:
#include <iostream> //for standard console I/O
#include <cstring> //for strlen()
char source="dlroW olleH"; //the source string
char target="dlroW olleH"; //the target string
register short int f; //the forward iterator
register short int r; //the reverse iterator
* this line gets the length of the source string. In this case, I
* made sure both strings were the same length. You could, after this
* point, allocate a target string just for the purposes of copying.
register const short int LEN=strlen(source);
* This is the "magic loop". What it does is set sthe forward iterator
* to zero, the reverse iterator to the last index to be copied, and
* loops until they are of equal size (or somehow they pass eachother).
* In each iteration, it increases the forward iterator and decreases
* the reverse iterator. The iterators work their ways from the ends
* of the string to the center.
for(f=0,r=LEN-1; f<r; f++,r--)
* The first line copies the first character in source to be
* copied into the last character in target to be written.
* The second line does the same, except it uses the last char
* in source to be read to write into the first position of
* target to be written.
std::cout<<target<<std::endl; //output the target string
return 0; //be nice to your creator.