C++ program to reverse a given string using using length() function
kw.cpp
#include<iostream>
#include<cstring>usingnamespacestd;intmain(){cout<<"———————————————————————————————————————————";cout<<"\nProgram to reverse a given string";cout<<"\n———————————————————————————————————————————";strings,r="";cout<<"\nEnter the string ";getline(cin,s);for(inti=s.length()-1;i>=0;i--){r=r+s[i];}cout<<"\nThe reverse string is "<<r;cout<<"\n———————————————————————————————————————————\n";}
Output
kodingwindow@kw:~$ g++ kw.cpp kodingwindow@kw:~$ ./a.out
———————————————————————————————————————————
Program to reverse a given string
———————————————————————————————————————————
Enter the string KODINGWINDOW
The reverse string is WODNIWGNIDOK
———————————————————————————————————————————
kodingwindow@kw:~$
C++ program to reverse a given string by swapping characters
kw.cpp
#include<iostream>
#include<cstring>usingnamespacestd;intmain(){cout<<"———————————————————————————————————————————";cout<<"\nProgram to reverse a given string";cout<<"\n———————————————————————————————————————————";chars[50],temp;cout<<"\nEnter the string ";cin>>s;inti=0,j=strlen(s)-1;for(i=0;i<j;i++,j--){temp=s[i];s[i]=s[j];s[j]=temp;}/* Another way, you can replace for loop with while loop
while(i<j)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
i++;
j--;
}
*/cout<<"\nThe reverse string is "<<s;cout<<"\n———————————————————————————————————————————\n";}
Output
kodingwindow@kw:~$ g++ kw.cpp kodingwindow@kw:~$ ./a.out
———————————————————————————————————————————
Program to reverse a given string
———————————————————————————————————————————
Enter the string KODINGWINDOW
The reverse string is WODNIWGNIDOK
———————————————————————————————————————————
kodingwindow@kw:~$
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.