How to reverse a string in c++ using reverse function
To reverse a string in C++ using the reverse
function, you need to follow these steps:
Include the necessary header file:
cpp #include <algorithm>
This header file provides thereverse
function that we will use to reverse the string.Declare and initialize a string variable:
cpp std::string str = "Hello, World!";
This line declares a string variable calledstr
and initializes it with the value "Hello, World!".Use the
reverse
function to reverse the string:cpp std::reverse(str.begin(), str.end());
Thereverse
function takes two iterators as arguments, representing the range of elements to be reversed. In this case,str.begin()
represents the iterator to the beginning of the string, andstr.end()
represents the iterator to the end of the string. By passing these iterators to thereverse
function, the stringstr
will be reversed.Print the reversed string:
cpp std::cout << str << std::endl;
This line prints the reversed string (str
) to the console.
Here is the complete code:
#include <iostream>
#include <algorithm>
int main() {
std::string str = "Hello, World!";
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
return 0;
}
When you run this code, it will output the reversed string: "!dlroW ,olleH".