Tutorial

Reverse String in C++

Published on August 3, 2022
Default avatar

By Sneh

Reverse String in C++

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In many situations, we may need to reverse a string in C++ programming. It may include just printing a reversed string. Or maybe in some cases need to reverse the string permanently at its address.

In this tutorial, we are going to learn how we can accomplish both the tasks. That too using different pre-defined as well as user-defined functions.

Reversing a String in C++

Reversing a string refers to the operation on a string, by which the sequence of characters in it gets reversed. For example, consider ‘str’ contains a string “JournalDev” in it.

After the reversal operation takes place on the string ‘str’, the content should get reversed. Hence now, ‘str’ should contain the string “veDlanruoJ”.

Now let us see how we can perform this reverse operation on C++ strings using various techniques.

Using reverse() function in C++

The built-in reverse function reverse() in C++ directly reverses a string. Given that both bidirectional begin and end iterators are passed as arguments.

This function is defined in the algorithm header file. The code given below describes the use of reverse() function,

#include <algorithm> 
#include<iostream>
#include<string>
using namespace std; 
int main() 
{ 
    string str = "Journal Dev reverse example"; 
    reverse(str.begin(), str.end()); 
	cout<<"\n"<<str; 
    return 0;
}

Output:

Use Of Reverse string in c++
Use Of reverse()

Using strrev()

strrev() is a pre-defined function in C++, defined inside the cstring.h header file. It is extensively applicable for reversing any C-string(character array).

Further, it only requires the base address of the string as its argument and reverses the string accordingly. Let us see how we can use the strrev() function in C++ to reverse strings.

#include<iostream>
#include<cstring>
using namespace std; 
int main() 
{ 
    char str[] ="Journal Dev reverse example"; 
    strrev(str);
	cout<<"\n"<<str; 
    return 0;
}

Output:

Reverse Using Strrev reverse string in C++
Reverse Using strrev()

The code above illustrates the working of the function strrev() very well. For a string ‘str’, the function reverses it successfully as we can see in the output itself.

Printing a String in reverse

In certain cases, we may not need to change the string but only print it in a reversed manner. This could be for constant strings that cannot be modified. We can print any string in a reversed pattern by using a loop. Let us see how.

#include<iostream>
#include<string>
using namespace std; 
int main() 
{ 
    string str="Journal Dev reverse example"; 
    int i;
    cout<<"Printing string in reverse\n";
    for(i = str.length() - 1; i >= 0; i--)
    {
      	cout<<str[i];
    }
    return 0;
}

Output:

Reverse Print
Reverse Print
  • In the above-given code, we have firstly initialized a string ‘str’.
  • Inside the for loop, while printing the string, note that we have initialized the iterator ‘i’ with a value str.length()-1. This means that we print the string character by character but, starting from the last index.
  • Note: length() returns the length of a string. So, for printing a string in reverse we should consider the last index which should be length()-1, since indexing starts from ‘0’ in a character array.

Making our own string reversing function My_rev()

Until now we learned how we can print a string in reverse as well as reverse the string using different pre-defined functions. Now let us create or define our own function named My_rev() to reverse a given string.

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
char *My_rev(char *str)
{
  int i,len=0,n;
  char temp;
  len=strlen(str);
  n=len-1;
  for(i = 0; i <=(len/2); i++)
  {
    temp=str[i];
    str[i]=str[n];
    str[n]=temp;
    n--;
  }
  return str;
}
int main()
{ 
    char My_string[]="Journal Dev reverse example";
	cout<<"Reverse string using My_rev()...\n";
    My_rev(My_string);
	cout<<My_string;
    return 0;
}

Output:

User defined My_rev() Output
User-defined My_rev() function Output
  • In the code above, My_rev() is a function that reverses a string, given the base address of the string is passed as an argument.
  • Inside the My_rev() function, *str is a pointer that stores the base address of the provided string. In our case, str points to the first element of the string My_string.
  • len stores the length of the string. Whereas, n is the index of the last element.
  • In the function, we try to swap individual characters of the string, from both ends. That means we go on swapping elements from the 0th and nth index until we get to the (len/2)th position. In the code above, the for loop does this swapping for us which technically reverses the string.
  • In the end, we return the base address str to the main() function. Where the string is printed using the cout function.

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Sneh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel