Here goes the link
Reverse the order of words in a string in place May 23, 2010
Q
Classic
Question
#:
Reversing
the
words
in
a
string
Write
a
function
to
reverse
the
order
of
words
in
a
string
in
place.
Ans:
Reverse
the
string
by
swapping
the
first
character
with
the
last
character,
the
second
character
with
the
second to‐last
character,
and
so
on.
Then,
go
through
the
string
looking
for
spaces,
so
that
you
find
where
each
of
the
words
is.
Reverse
each
of
the
words
you
encounter
by
again
swapping
the
first
character
with
the
last
character,
the
second
character
with
the
se cond‐to‐last
character,
and
so
on.
//Mysolution inplace reversal of order of words //inplace reversal of order of words #include<stdio.h> #include<string.h> int main() { char s[1000],c; int i,j,k,l; gets(s); l=strlen(s); for(i=0;i<l/2;i++){ c=s[i]; s[i]=s[l-i-1]; s[l-i-1]=c; } for(i=0;s[i]!='\0';){ j=i; while(s[i]!=' ') { if(s[i]=='\0') {break;} i++; } for(k=j,l=i-1;k<=l;k++,l--){ c=s[k]; s[k]=s[l]; s[l]=c; } if(s[i]==' ') i=i+1; } puts(s); return 0; }
Sample
input: This world is beautiful
ouput: beautiful is world This
input: This is a sample input output
output: output input sample a is This
Recent Comments