Custom Search

Thursday, March 15, 2007

C - Review II 28

28. Write a program to reverse the words in a string

Example: input: Hello how are you

output: you are how Hello


Solution:

void main()
{
unsigned char old_name[]={"My name is amit agrwal"},new_name[100];
int i,i_old,j,k=0;
i_old=strlen(old_name)-1;
for(i=i_old;i>=0;i--)
{
if(old_name[i]==' ' || i==0)
{
j=i;
if(i!=0)
j++;
for(;j<=i_old;j++)
new_name[k++]=old_name[j];
new_name[k++]=' ';
i_old=i-1;
}
}
new_name[k]=NULL;
printf("%s",new_name);


the solution to this problem of reversing the string is :

/*reverse a string - word by word */

#include"stdio.h"
int main()
{

char a[100]="My name is Amit Agarwal",ch,temp[100];
int i,length,j,k,l;
printf("Enetr the string\n");
for(i=0;a[i]!='\0';i++);
length=i;k=0;

for(i=length-1,j=length-1;a[i]!='\0';i--)
{
if(a[i]==' ')
{
for(l=i+1;l<=j;l++,k++)
temp[k]=a[l];
j=i-1;
temp[k]=' ';k++;
}
}

if(a[i]=='\0')
{
for(l=i+1;l<=j;l++,k++)
temp[k]=a[l];

}
temp[k]='\0';
printf("%s",temp);
return 0;
}

In the above 2 solutions u r using temporary array. I told that time and space complexity must be O(n).


my answer is without using any temporary storage is
#include"stdio.h"
#include"string.h"
void rev(char *s, int st, int e)
{
int i;
char ch;
for(i=0;i<=(e-st)/2;i++)
{
ch= s[st+i];
s[st+i]=s[e-i];
s[e-i]=ch;

}

}
void main()
{
int i, j, len;
char s[80], ch;
clrscr();

gets(s);

rev(s,0,strlen(s)-1);

printf("%s",s);
j=0;
for(i=0;i< strlen(s);i++)
{
if(s[i]==' ')
{
rev(s,j,i-1);
j=i+1;
}
}
rev(s,j,strlen(s)-1);
printf("\n\n%s",s);

getch();
}

No comments: