Reverse a string in C++
Reversing a string means the last character should be the first character the second last should be the second and so on. Reversing a string is a basic operation in programming and in C++, we can do that using the std::reverse() algorithm provided in the STL <algorithm> library.
Syntax of std::reverse()
std::reverse(begin_itr, end_itr);
where,
- begin_itr is the iterator to the beginning of the range.
- end_itr is the iterator to the end of the range.
C++ Program to Reverse a String in C++
C++
// C++ program to reverse a string using the reverse() // function #include <algorithm> #include <iostream> using namespace std; int main() { string str = "Hello, World!" ; cout << "Original string: " << str << endl; // Reverse the string using the reverse() function reverse(str.begin(), str.end()); cout << "Reversed string: " << str << endl; return 0; } |
Output
Original string: Hello, World! Reversed string: !dlroW ,olleH
Time Complexity: O(n)
Auxiliary Space: O(1)
How to Reverse a String in C++?
In C++, strings are the sequence of characters that are used to represent textual data. In this article, we will learn how to reverse a string in C++.
For Example,
Input: myString = "Hello, GFG!" Output: myString = "!GFG ,olleH"