Reverse a String in C++
By: Grant Braught
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;
}
}
Archived Comments
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++