Programming Tutorials

Reverse a String in C++

By: Grant Braught in C++ Tutorials on 2011-01-27  

This sample C++ program reverses a String and at the same time demonstrates the Pass by Reference parameters in C++ functions.
#include <iostream.h>

// Function prototypes...
void Reverse(string &theWord);

int main(void)
{
       	string MyWord;
       	
       	cout << "Enter a word to be reversed: ";
       	cin >> MyWord;
        
        cout << "Before Reverse:" << endl;
        cout << " MyWord = " << MyWord << endl << endl;
        
       	Reverse(MyWord);
        
        cout << "After Reverse:" << endl;
        cout << " MyWord = " << MyWord << endl << endl;
                
        return(0);
}

void Reverse(string &theWord)
{       // Reverse the string contained in theWord.

        int i;
        char temp;
        
        for (i=0; i<theWord.length()/2; i++)
        {
        	temp = theWord[i];
        	theWord[i] = theWord[theWord.length()-i-1];
        	theWord[theWord.length()-i-1] = temp;
        }
}  





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)