C++ Program to Reverse a Given String
This page contains a C++ program that reverses a given string. The program uses basic string manipulation techniques to achieve this task.
Program Explanation
The C++ program to reverse a string follows these steps:
- Include necessary headers: Use the
#include
directive to include required libraries. - Main Function: The
main
function is the entry point of the program. - Input String: Define a string that you want to reverse.
- Reverse the String: Use a loop to reverse the string by swapping characters from the beginning and end.
- Print the Result: Output the reversed string to the console.
C++ Program Code
#include <iostream>
#include <string>
/**
* Function to reverse a given string.
* @param str the string to be reversed
* @return the reversed string
*/
std::string reverseString(const std::string &str) {
std::string reversed = str;
int n = reversed.length();
// Swap characters from the beginning and end
for (int i = 0; i < n / 2; ++i) {
std::swap(reversed[i], reversed[n - i - 1]);
}
return reversed;
}
/**
* Main function which is the entry point of the program.
*/
int main() {
// Define the string to be reversed
std::string original = "Hello, World!";
// Call the reverse function and store the result
std::string reversed = reverseString(original);
// Print the original and reversed strings
std::cout << "Original String: " << original << std::endl;
std::cout << "Reversed String: " << reversed << std::endl;
return 0;
}
Program Details
The program contains the following components:
reverseString
Function: A function that takes a string as input, reverses it by swapping characters, and returns the reversed string.main
Function: The entry point of the program where the string is defined and the reverse function is called.
Running the Program
To run the program:
- Save the code in a file named
ReverseString.cpp
. - Compile the program using the command:
g++ -o ReverseString ReverseString.cpp
. - Run the compiled program using the command:
./ReverseString
.
Explanation of the C++ Program:
- Include Headers:
#include <iostream>
: For input and output operations.#include <string>
: For string operations.
- reverseString Function:
- Takes a
const std::string &str
as input and returns a reversed string. - Creates a copy of the input string to reverse it.
- Uses a loop to swap characters from the beginning and end of the string until the middle of the string is reached.
- Takes a
- Main Function:
- Initializes a string
original
with a value to be reversed. - Calls the
reverseString
function and stores the result inreversed
. - Prints both the original and reversed strings to the console.
- Initializes a string