In C++, reversing a string is a basic operation in programming that is required in various applications, from simple and complex algorithms. Reversing a string in place involves changing the characters of the string directly without using input-dependent additional storage. In this article, we learn how to reverse a string in place in C++.
For Example,
Input: myString = "Hello, World!" Output: myString = "!dlroW ,olleH"
Reverse a String In-Place in C++
The std::reverse() function provided by the C++ STL library can be used to reverse the string in place. This function takes the iterator to the beginning and the end of the string.
Syntax of std::reverse()
std::reverse(begin, end)
The begin and end can be either an iterator or a pointer.
C++ Program to Reverse a String In-Place
// C++ program to reverse a string in place #include <algorithm> #include <iostream> #include <string> using namespace std;
int main()
{ // Initialize the string
string str = "Hello, World!" ;
// Reverse the string
reverse(str.begin(), str.end());
// Output the result
cout << "Reversed string is: " << str << endl;
return 0;
} |
Reversed string is: !dlroW ,olleH
Time Complexity: O(n)
Auxiliary Space: O(1)
Note: In an in-place algorithm, additional space can be used as long as it is not dependent on the input.