+92 332 4229 857 99ProjectIdeas@Gmail.com

How to reverse a string (C++)


How to reverse a string
Reverse() takes the string as an input parameter and returns the reversed string.
Example
For example. if the input to this function is Saad Bin Saulat, then it will return  taluaS niB daaS.
Summary of Reverse()
Reverse() starts from the first index of the string and goes to the half length of the string. At each iteration it swap 2 elements of the string, i.e
In first iteration, it swaps first and the last element,
In the second iteration, it swaps second and the second last element,
And so on…
Reverse() uses Swap() function to swap 2 elements of the string.
Summary of Swap()
Swap() takes 2 input parameters which are the pointers to the 2 elements to be swapped.
First a temporary pointer temp is declared,
char * temp;
which holds the data during swapping,
then the second element var2 is stored in temp
temp = var2;
then the first element var1 is placed in var2
var2 = var1;
and at the last the value of temp is assigned to var1
var1 = temp;


Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

void Swap ( char * var1 , char * var2 )
{
       char * temp;
       temp = var2;
       var2 = var1;
       var1 = temp;
}

char * Reverse( char str[] )
{
       int length = strlen( str );
       int j = length - 1;
       int temp;

       for ( int i = 0; i < length / 2; i++ , j-- )
       {
              Swap( str[i] , str[j] );
       }

return str;
}

int main()
{
       char str[]="Saad Bin Saulat";

       cout << Reverse( str ) << endl;
       cout << Reverse( str ) << endl;

       _getche();
       return 0;
}

Output
taluaS niB daaS
Saad Bin Saulat

0 comments: