27+ CPP Programs to Reverse a String

This post contains a total of 27+ Hand-Picked CPP Program examples to Reverse a String, with Source Code. All the Programs are made using C++ Programming language.

You can use the source code of these programs for educational use with credits to the original owner.

Related Posts

Click a Code to Copy it.

1. By tooselfish

Made by tooselfish. Simple C++ program to reverse a string. ( Source )

#include<iostream>
#include<algorithm>
#include<string>


int main() {
    
    std::string str{};
    std::getline(std::cin, str);
    std::cout << "Your string is             :  " << str << std::endl;
    
    if( std::cin.fail() ){
        std::cerr << "Wrong input!\n";
        return 1;
    }
    
    // reverse the string
    reverse(str.begin(), str.end());
    
    // output your reverse string
    std::cout << "\nThis is your reverse string:  " << str << std::endl;
    
    return 0;
}

2. By RICHA ๐Ÿ‡ฎ๐Ÿ‡ณ

Made by RICHA ๐Ÿ‡ฎ๐Ÿ‡ณ. The program prints out both the entered and the reversed string. ( Source )

#include <iostream>

using namespace std;
int main() 
  {
   int i,len;
   string str;
   cout<<"Enter the string \n";
   cin>>str;
   cout<<"The original string is:"<<str<<"\n";
   cout<<"The reverse string is:";
   len=str.length();
   for(i=len-1;i>=0;i--)
   {
       cout<<str[i];
   }
   return 0;
}

3. By BroFar

Made by BroFar. Enter your string inside “string o”. ( Source )

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

// Function to reverse a string in-place in C++
void reverse(string &o){
             int f = o.length();
    
for (int b = 0; b < f/2; b++)
        std::swap(o[b], o[f-b-1]);
//swap method used 
}

// main function
int main(){
    
  std::string o("BroFarOps Creations LLC");
    cout << "Before : "+o+"\n";
    reverse(o);
    cout << "After : "+o;

    return 0;
}

4. By ChillPill ๐ŸŒถ

Made by ChillPill ๐ŸŒถ. The program uses two methods to reverse a string, first method needs the string input and the second method requires you to manually enter the string inside the code. ( Source )

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
    string s;
    getline(cin,s);
    //method one
    stack <char> stck;
    for(char c:s) stck.push(c);
    while(stck.size()>0) {
        cout<<stck.top();
        stck.pop();
    }
    cout<<endl;
    //method two
    string s2="dlrow olleh";
    for(int i=s2.size();i>=0;i--) cout<<s2[i];
    return 0;
}

5. By Swapnil More

Made by Swapnil More. ( Source )

#include <iostream>
using namespace std;

int main() {
    int i,m;
    string arr;
    cout<<"Enter words: ";
    getline(cin,arr);
    cout<<arr<<endl;
    m=arr.length();
    for(i=m;i>=0;i--){
        cout<<arr[i];
    }
    return 0;
}

6. By Dร…RK PRรŒร‘ร‡ร‰

Made by Dร…RK PRรŒร‘ร‡ร‰. ( Source )


#include <iostream>
using namespace std;

string revstr (string str){
    string rev;
    for(int i = str.size() - 1; i>=0 ; --i){
        rev = rev + str[i] ;
    }
    return rev;
}

int main() {
   
    string test;
    cout << " Enter text to make it reversed " << endl << endl;
   getline(cin,test);
    cout << " Reversed text is: \n    " << revstr(test);
}

7. By Sololearn

Made by Sololearn. You need to enter the string inside ‘string text = “Just for fun”;. ( Source )

#include <iostream>
#include <string>
using namespace std;

string reverseStr(string x)
{
	string temp = "";
	int len = x.length();

	for (int i = len - 1; i >= 0; --i)
	{
		temp += x[i];
	}
	return temp;
}

int main()
{
    //sample text
	string text = "Just for fun";
	
	cout << reverseStr(text);

	return 0;
}

8. By ChillPill ๐ŸŒถ

Made by ChillPill ๐ŸŒถ. Enter the input string in ‘x{“backwards”};’. ( Source )

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
    for(stack<char,string> x{"backwards"};
        !x.empty();
        x.pop())
        cout << x.top();
    return 0;
}

9. By silentlearner

Made by silentlearner. C++ program to reverse and input string. ( Source )

#include <iostream>

int main() {
    std::string word, rev_word;
    std::getline(std::cin, word);
    
    for(int i=word.length(); i>=0; i--){
        rev_word += word[i];
    }
    
    std::cout<<rev_word;
    return 0;
}

10. By Chokri ZAGROUBA

Made by Chokri ZAGROUBA. C++ Reverse string with for loop. ( Source )

#include <iostream>
#include <string.h>
using namespace std;

int main() {
    int i;
    char *str;
    for(i = 0, str = "++c nraelolos";
    i < strlen (str)+1;
    cout << str[strlen(str)-i], i++);
    return 0;
}

11. By Jay

Made by Jay. Convert an integer into a string then reverses the string. Enter an integer to be converted into a string data type and reversed, Try Entering a number that ends in a zero (0) . ( Source )

// How it works..
#include <iostream>
// #include <iostream>
// provides access to cin / cout
#include <string>
//#include <string>
// provides access to string
#include <sstream>
//#include <sstream> 
// ostringstream
#include <algorithm>       
//  provides access to reverse

using namespace std;
// includes entire std namespace. allows us to reference things without qualification. ie. cout vs std::cout and cin vs std::cout
// caveat: You can create things with conflicting names if you make the entire namespace available. So just be sure to be creative and not namethings the same as functions that would be obviously available and you should be ok.

int main() {
    unsigned int myNumber;
// declare a new iteger. 
// This int type can only store whole numbers. 
// The int data type is fine for our needs. 
// Note: We have used the unsigned modifier on int because we won't be dealing with negative numbers here.
    
    string numberString;
// declare a new string numberString. This is where we will store the converted number. Anything stored here we actually be a char array. made up of characters.
    unsigned int ReversedNumber;
    
    
    cin >> myNumber;
// prompt the user to enter a number
    
    if(!std::cin) {
// if the data entered by the user is not of the correct type. Tell them. and the program will end.
        cout << "Enter a number next time please";
// clear the cin buffer and ignore any errors before we go.
        std::cin.clear();
        std::cin.ignore();
        
    }
    else {


/*
The user must of entered a number. Now we can get to work. 
*/
    
        ostringstream convert;
/* 
Create an output stream class to operate on strings.
we will call it convert as that is what we will be using it for. (converting an int to a string)
For more information on ostringstream see:
http://www.cplusplus.com/reference/sstream/ostringstream/
*/
        convert << myNumber;
   // put myNumber as int into convert the stringstream. this converts the number into a series of characters
  
   
        numberString = convert.str();
// put the stringstreams characters into a string. Remembering that the sequence of characters held in convert can be accessed directly as a string object by using the member str.
   
        reverse(numberString.begin(), numberString.end());
   // reverse the string by using the reverse funtion found in the algorithm header
   // see: http://www.cplusplus.com/reference/algorithm/reverse/
   
        //convert reversed number back to an integer using istringstream this time
        istringstream convertBack(numberString);
        // see http://www.cplusplus.com/reference/sstream/istringstream/
        convertBack >> ReversedNumber;
              
        cout << "Reversed as String: " << numberString << "\n";
        //output the string to the screen
        cout << "Reversed as Integer: " << ReversedNumber << "\n";
        //output the integer to the screen
    
    }
    
    // end the program gracefully.
    return 0;
}

12. By Saurabh Tiwari

Made by Saurabh Tiwari. ( Source )

#include <iostream>
#include <cstring>
using namespace std;int main()
{char arr[100]; 
cin.getline(arr,100); 
for(int i=strlen(arr);i>=0;i--)
cout<<arr[i]; 
}

13. By ChillPill ๐ŸŒถ

Made by ChillPill ๐ŸŒถ. Reverse text string using iterator. ( Source )

#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;

template <class T>
class R{
    T container;
    public:
    using iterator = reverse_iterator<typename T::iterator>;
    R(T x):container{x}{}
    iterator begin(){
        return iterator{container.end()};
    }
    iterator end(){
        return iterator{container.begin()};
    }
};

int main() {
    string s{"backwards"};
    for(auto & c: s) cout << c;
    cout << endl;
    
    R<decltype(s)> rs{s};
    for(auto & c: rs) cout << c <<" ";
    cout << endl;
    
    for(auto & c: R<decltype(rs)>{rs})
        cout << c <<" ";
    cout << endl;
    
    for(auto & n: R<vector<int>>{{1,2,3,4,5}})
       cout << n;
    return 0;
}

14. By Lorenzo Busolini

Made by Lorenzo Busolini. ( Source )

#include <iostream>
#include <string>
using namespace std;
int main() {
	string parola;
	
cin >> parola;
cout << " your word: " << parola << endl;
for (string::reverse_iterator rit=parola.rbegin(); rit!=parola.rend(); ++rit)
{
	 cout << *rit;
	 }
 	
	return 0;
}

15. By Mehak Jain

Made by Mehak Jain. ( Source )

#include <iostream>
#include<string.h>
using namespace std;

int main() 
{
  char a[20];
  int t;
  cin>>a;
  int l=strlen(a);
  for(int i=0,j=l-1;i<=j;i++,j--)
   {  
       t=a[i];
       a[i]=a[j];
       a[j]=t;
   }
   cout<<"reverse string :  ";
   cout<<a;
   
    return 0;
}

16. By BARBIE ZAVERI

Made by BARBIE ZAVERI. C++ Reverse string using inheritance. ( Source )

#include <iostream>
using namespace std;

class Base
{
   public : 
       char str1[10] ;
       char str2[10];
       void getdata()
       {
          cout << "Enter String 1 : " ;
          cin >> str1;
          cout << str1 << endl;
          cout << "Enter String 2 : ";
          cin >> str2;
          cout << str2 << endl;
       }
};

class Derived : public Base
{
   public : 
        int i;
        int getlength( char s1[10])
        {
           for (i=0;s1[i]!='\0';i++) ;
           {
               return i-1;
           }
        }
        
        void reverse()
        {
           int n= getlength (str1) ;
           for(int i=n;i>=0;i--)
           {
              cout << str1[i] ;
           }
           cout << endl;
        }
        
        void compare()
        {
           int i,j, flag=0;
           int n1=getlength (str1);
           int n2=getlength (str2);
           for(i=0,j=0;i<n1,j<n2;i++,j++)
           {
           if(str1[i]!=str2[j]) 
           {
              flag=1; 
           }
           }
           if(flag==1)
           {
              cout << "Strings are not equal..." ;
           }
           else
           {
              cout <<"Strings are equal..."; 
           }
        }
};

int main() {
    Derived obj;
    obj.getdata ();
    cout << "Reverse String is : ";
    obj.reverse();
    obj.compare ();
    return 0;
}

17. By Davood Abdollahi

Made by Davood Abdollahi. Enter your string inside ‘char myText[] = “Hello World!’. ( Source )

#include <iostream>
using namespace std;

int main() {
   char myText[] = "Hello World!";
   int numberOfCharacters = sizeof(myText) - 1;
   char *pStart = myText;
   char *pEnd = myText + numberOfCharacters - 1;
   while (pStart < pEnd) {
   	char save = *pStart;
   	*pStart = *pEnd;
   	*pEnd = save;
   	pStart++;
   	pEnd--;
   }
   cout << myText << endl;
   return 0;
}

18. By djorborn

Made by djorborn. Enter your input in ‘string t’. ( Source )

#include <iostream>
#include <string>
using namespace std;

int main() {
    string t = "I am the string;gnirts eht ma I oN";
    
    cout << string(t.rbegin(), t.rend()) <<endl;
    
    return 0;
}

19. By MrCoder

Made by MrCoder. ( Source )

#include <iostream>
using namespace std;

int main() {
    string nm;
    cin >> nm;
    cout << "Your string: " << nm << endl;
    int len = nm.length();
    cout << "Reversed String: ";
    for(int i = len; i > -1; i--)
    { 
       cout << nm[i];
    }
    return 0;
}

20. By Baltazarus

Made by Baltazarus. ( Source )

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

void ReverseSystem() {
    cout << "Type what you want to reverse: " << endl;
    string tool;
    cin >> tool;
    reverse(tool.begin(), tool.end());
    cout << "Reverse:\n\n" << tool << endl;
}

int main(void) {

    ReverseSystem();
      
    return 0;
}

21. By code0rdie

Made by code0rdie. ( Source )

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;


int main() {
   
    //Declare an extract input from user.
    string inp;
     getline(cin, inp);
    
    cout << " String Input : "<< inp << endl;
    
    cout << " Reversed String Output : ";
    
    
   // reverse string here..
   
   reverse(inp.begin(),inp.end());
   
   
   cout <<inp<<endl;
    


    return 0;
}

22. By Michail Getmanskiy

Made by Michail Getmanskiy. Enter the string inside ‘instr = “hello”;’ ( Source )

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    string instr;
    instr = "hello";
    cout << "\"" << instr << "\"" << endl;
    std::reverse(instr.begin(), instr.end());
    cout << "\"" << instr << "\"" << endl;
    return 0;
}

23. By Gone

Made by Gone. ( Source )

#include <iostream> 

using namespace std; 

void reverse(const string& a); 

int main() 
{ 
string str; 
cout << " Your entered string " << endl; 
getline(cin, str); 
reverse(str); return 0; 
  } 
  
void reverse(const string& str) 
{ 
  size_t numOfChars = str.size();     if(numOfChars == 1) 
  cout << str << endl; 
  else { 
  cout << str[numOfChars - 1];             reverse(str.substr(0, numOfChars - 1)); 
  } 
  
}

24. By Tamil Selvan

Made by Tamil Selvan. ( Source )

#include <iostream>
#include <vector>
using namespace std;

int main(){
    int n;
    cin >> n;
    vector<int> arr(n);
    for(int arr_i = 0;arr_i < n;arr_i++){
       cin >> arr[arr_i];
    }
    for(int i=n-1;i>=0;i--)
    {
        cout<<arr[i]<<" ";//reverse string 
    }
    return 0;
}

25. By Varun Verma

Made by Varun Verma. C++ string reverse using pointer n recursion. Enter your string in ‘char str[]= “india”. ( Source )

#include <iostream>
#include <string>
using namespace std;
void rev(char *);
int main() {
   char str[]= "india";
   rev(str);
    return 0;
}
     void rev(char *ptr)
       {
           if(*ptr)
               {
                   rev(ptr+1);
                   cout<<*ptr;
               }
       }

26. By Gustavo Gauthier

Made by Gustavo Gauthier. ( Source )

#include <iostream>
#include <algorithm>
using namespace std;

int main() {

  cout<<"+----------------------------------------------+\n"
        "|SOLOLEARN - EVERYONE CAN CODE                 |\n"
        "|CODE #17                                      |\n"
        "|Reverse a string                              |\n"
        "|Codes Series by Gustavo Gauthier for SoloLearn|\n"
        "|==============================================|\n"
        "|Enter a string to reverse it                  |\n"
        "+----------------------------------------------+\n";
        
  string str;
  cin>>str;
  cout<<"\nThis is the string: "<<str;
  
  std::reverse(str.begin(), str.end());
  cout<<"\nThis is the string reversed: "<<str;
  
  cout<<"\n_____________________________________________\n"
      "ACHTUNG!: You may use everything I code but,\n"
      "please, be so kind to give me credit. Grazie.";
  return 0;
}

27. By Chris

Made by Chris. ( Source )

#include <iostream>
#include <string>

int main() 
{
	std::string s;
	std::getline(std::cin, s);
	
	int i = 0;
	int j = s.size() - 1;
	
	while (j > i) {
		char temp;
		temp = s[j];
		s[j] = s[i];
		s[i] = temp;
		++i;
		--j;
	}
	
	std::cout << s << std::endl;
	
	return 0;
}

28. By Med Arezki

Made by Med Arezki. ( Source )

#include <iostream>
#include <string>
using namespace std;

int main()
{
   string rec;
   char a;
   
   int j(0);
   string word;
   cout<<"Enter your sentence : ";
   getline(cin,word);
   
   for (int i=word.size()-1;i>=0;i--)
   {
   	a=word[i];
   	rec.push_back(a);
   	j++;
   }
   int i=0;
   cout<<endl;
   cout<<"Your word :"<<endl;
   do
   {
   	cout<<rec[i];
   	i++;
   }while(i<j);
	return 0;
}