Reverse a String in C++

By: Grant Braught Viewed: 192 times  Printer Friendly Format    


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

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


Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial