C++ Program to Reverse a String

Here you will get C++ program to reverse a string. We will learn two ways to do this, using user-defined and inbuilt functions.

The user is asked to enter a string and then the reverse of the string is displayed.

For example:

  • Input String: hello
  • Output String: olleh

User Defined Function

In this method, we will use a loop to reverse the string.

Output:

Enter any string:i love c++
++c evol i

Inbuilt Function

This method uses the inbuilt function reverse() from the algorithm header file.

Output:

Enter any string:The Crazy Programmer
remmargorP yzarC ehT

Comment below if you are facing any difficulty understanding the above program.

9 thoughts on “C++ Program to Reverse a String”

  1. I think this logic is good than using multiple for loops ……….

    #include
    #include
    #include

    using namespace std;

    int main(){
    char str1[20],str2[20];
    int i=0,len;

    cout<<"Enter a String : ";
    gets(str1);
    len = strlen(str1);

    while(len>=0){
    str2[i] = str1[–len];
    i++;
    }
    str2[i]='';

    cout<<"Reversed String : "<<str2;

    return 0;
    }

    1. this will work for sure

      #include
      #include
      #include

      void reverse(char str[ ],int) ;

      void main()
      {
      char str[80];
      clrscr();
      cout<<"Enter the string : " ;
      cin.getline(str,80);
      int len=strlen(str);
      reverse(str,len);
      getch();
      }

      void reverse(char str1[ ] , int length)
      {
      int mid=length/2;
      length – – ;
      for(int i=0; i<mid; i++)
      {
      char temp=str1[i];
      str1[i]=str1[length];
      str1[length]=temp;
      length – – ;
      }
      cout<<"\t\t Reverse of the String is : " ;
      cout<<str1;
      }

  2. #include
    #include
    #include
    void main()
    {
    char a[2100],a2[100],t;
    cout<<"enter the array :";
    gets(a);
    t=strlen(a);
    for(int i=0;a[i]!='\0';++i)
    {
    a2[t-i-1]=a[i];
    }
    for(i=0;i<t;++i)
    cout<<a2[i];
    }

  3. Harikrishna D S

    #include
    #include
    #include
    using namespace std;

    int main()
    {
    char str[50];
    int str_len;
    cout<<"Enter the string"<<endl;
    gets(str);
    str_len=strlen(str);
    int start=0, end=str_len;

    for(int i=0;i<str_len;i++)
    {
    swap(str[i],str[str_len-1]);
    str_len–;
    }
    cout<<str;
    }

Leave a Comment

Your email address will not be published. Required fields are marked *