WAP to reverse a string
Objective
Write a C++ program to reverse a string.
Algorithm / Approach
- Include the
<algorithm>header file. - Read a string into
s1. - Call the built-in reverse function using iterators:
reverse(s1.begin(), s1.end()). - Print the modified string.
main.cpp
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
string s1;
cout<<"Enter a string : ";
getline(cin,s1);
reverse(s1.begin(),s1.end());
cout<<"Reverse String = "<< s1;
return 0;
}
Expected Output
Enter a string : cprowess Reverse String = sseworpw
Explanation of the Program
- The
<algorithm>library in C++ provides a massive suite of highly optimized functions for manipulating data collections. - The
reverse()function takes two "iterators" (pointers that define a start and end boundary) and perfectly reverses the elements between them in-place, without requiring a second backup string.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)