0 Replies - 307 Views - Last Post: 21 October 2007 - 12:22 PM

#1 jjhaag   User is offline

  • me editor am smartastic
  • member icon

Reputation: 48
  • View blog
  • Posts: 1,789
  • Joined: 18-September 07

Reversing a std::string with 4 different methods

Posted 21 October 2007 - 12:22 PM

Description: copy/paste and go. Should be fairly simple to have the function return the reversed string instead, in case you want to preserve the order of the original.Four methods to reverse a std::string, replacing the original with the mirrored version. Uses the reverse() algorithm, random-access and reverse iterators, and a more traditional element-by-element reversal using a temporary swap value.
/* reverseString()
 * 
 * jjhaag (jjhaag AT dreamincode.net)
 * 21 October 2007
 * 
 * Reversing a std::string using one of four different methods.  String 
 * is passed by reference, and the reversed string replaces the original.
 * 
 * Demonstrates string manipulation, the reverse method from <algorithm>,
 * and the use of both random-access and reverse iterators.
 * 
 * Dependencies:  requires <algorithm> for the first method, and of course
 * <string>.
 */
#include <algorithm>
#include <string>

void reverseString(std::string& str, int method) {
    switch (method) {
        case 0: {
            //  Reverse string using 'reverse' method from <algorithm>
            reverse( str.begin(), str.end());
            break;
        }
        
        case 1: {
            //  reverse with std::string assign() method and reverse iterators
            //  assigns string into itself, backwards
            str.assign(str.rbegin(), str.rend());
            break;
        }
        
        case 2: {
            //  reverse using individual element access and a temporary swap value
            //  this is a pretty common method of doing reversals
            for (int i=0; i<(int)str.size()/2; ++i) {
                char temp=str.at(i);
                str.at(i)=str.at(str.size()-i-1);
                str.at(str.size()-i-1)=temp;
            }
            break;
        }
        
        case 3: {
            //  reverse using random-access iterators and a temporary swap value
            //  similar to above, but with iterators instead of an incremented index
            std::string::iterator iter1=str.begin();
            std::string::iterator iter2=str.end()-1;
            while (iter1<iter2) {
                char temp=*iter1;
                *iter1=*iter2;
                *iter2=temp;
                ++iter1;
                --iter2;
            }
            break;
        }
        default: {
            //  does nothing, no reversing of the string
        }
    }
    
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1