C++ program to reverse a given string using using length() function
kw.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    cout<<"———————————————————————————————————————————";
    cout<<"\nProgram to reverse a given string";
    cout<<"\n———————————————————————————————————————————";
    string s, r = "";
    cout<<"\nEnter the string ";
    getline(cin, s);
    for (int i = 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>
using namespace std;
int main()
{
    cout<<"———————————————————————————————————————————";
    cout<<"\nProgram to reverse a given string";
    cout<<"\n———————————————————————————————————————————";
    char s[50], temp;
    cout<<"\nEnter the string ";
    cin>>s;
    int i = 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:~$
Advertisement