Interview

How to reverse a string in C++?

Solution 1

Using reverse inbuild method from string.h


<predata-previewers=””>#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello";
reverse(greeting.begin(), greeting.end());
cout << greeting << endl;
}

Solution 2

Using inbuild swap method


<predata-previewers=””>#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;
}

Solution 3

Without any inbuild function and by using temporary variable.


<predata-previewers=””>#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;
}

Solution 4

Using Constructors and iterators


<predata-previewers=””>// 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;
}

Solution 5

Without using any inbuild functions and any temporary variables


<predata-previewers=””>// 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;
}

Solution 6

Using recursion


<predata-previewers=””>#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;
}

Related Articles

Back to top button