37
Write a program to reverse a string in C++
There are numerous ways to solve this problem. Let’s start with the simplest one – Using the inbuilt “reverse” function. In the example below, the string to be reversed is initialized within the program to a string variable “greeting”. As a challenge, you can try to implement by prompting the user to Enter the string to be reversed.
reverse() is a predefined function in header file algorithm. It is defined as a template in the above mentioned header file. It reverses the order of the elements in the range [first, last) of any container. The time complexity is O(n). Click here to learn more about reverse().
Â
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello";
reverse(greeting.begin(), greeting.end());
cout << greeting << endl;
}
#include <iostream>
using namespace std;
int main() {
string greeting = "Hello";
int len = greeting.length();
int n=len-1;
for(int i=0;i<(len/2);i++){
//Using the swap method to switch values at each index
swap(greeting[i],greeting[n]);
n = n-1;
}
cout<<greeting<<endl;
}
#include <iostream>
using namespace std;
int main() {
string greeting = "Hello";
int len = greeting.length();
int n=len-1;
for(int i=0;i<(len/2);i++){
//Using temp to store the char value at index i so
//you can swap it in later for char value at index n
char temp = greeting[i];
greeting[i] = greeting[n];
greeting[n] = temp;
n = n-1;
}
cout<<greeting<<endl;
}
// A simple C++ program to reverse string using constructor
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
//Use of reverse iterators
string rev = string(str.rbegin(), str.rend());
cout << rev << endl;
return 0;
}
// C++ Program to reverse a string without
// using temp variable
#include <iostream>
using namespace std;
// Function to reverse string and return revesed string
string reversingString(string str, int start, int end)
{
// Iterate loop upto start not equal to end
while (start < end)
{
// XOR for swapping the variable
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];
++start;
--end;
}
return str;
}
int main()
{
string s = "HelloW";
int len = s.length();
cout << reversingString(s, 0, len-1);
return 0;
}
#include <iostream>
using namespace std;
// Recursive function to reverse a given string
// Note string is passed as reference parameter
void reverse(string &str, int k)
{
static int i = 0;
// if we have reached the end of the string
if (k == str.length())
return;
reverse(str, k + 1);
if (i <= k)
swap(str[i++], str[k]);
}
int main()
{
string str = "Hello";
reverse(str, 0);
cout << "Reverse of the given string is : " << str;
return 0;
}