Saturday, January 29, 2011

Reversing words in a string in cpp (c plus plus)

Now , we wanna do something chilly , user will enter a string as
i am a boy
our program should return
boy a am i

Here is a program for this logic . .

******************* Start of Program ************************

// Reversing words in a string

#include"iostream.h"
#include"conio.h"
#include"stdio.h"

void main()
{
clrscr();
char str1[50],str2[50];
cout<<"Enter a String :: ";
gets(str1);

int h=0;
while(str1[h]!='\0') // to get number of chracters in sub string
{
h++;
}

int flag=h-1;
int u=0;


int d=0;
for(int i=h-1;i>=0;i--)
{
if(str1[i]==' '||i==0)
{
u=i;
while(u<=flag)
{
str2[d]=str1[u];
d++;
u++;
}
if(i!=0)
{
str2[d]=' ';
d++;
}
flag=i-1;
}
} str2[d]='\0';

cout<<"\n\nProcessed string is :: "<<(str2);
getch();
}