Somone please help me writing a code for "Reverse a word in a String" in c..
Ex: My name is XYZ
o/p:XYZ is name My

Edited 6 Years Ago by deepak.hm123: n/a

//Declare an str
char str[50],str1[50];
accept
gets(str);
for(init to end of str;>0;var--)
store str1[1] = str[n]
print str1;

Edited 6 Years Ago by Rahul.menon: n/a

i couldn't understand the "for" loop and "accept" statement. Can you please explain how it works.

Here's my code

void main()
{
 char str[60],str1[60];
 int i = 0,j=0,k=0,end =0;
 clrscr();
 gets(str);

 while(i<strlen(str))
 {
  if(str[i] == ' ' || !str[i+1])
  {
     str1[k] = ' ';
     k++;

     if(!str[i+1])
	i++;

     for(j = i-1;j>=end;j--)
       {
	str1[k]= str[j];
	k++;
       }
     end = i;
   }
   i++;
 }

   k--;
   for(;k>0;k--,printf("%c",str1[k]));
}

Its adding some extra spaces i will check and find.
if have got some better code pls tell.

If its just the words that you need to reverse and not the letters themselves, use the code I wrote here to separate the words in a string: http://www.daniweb.com/forums/thread319472.html

But instead of writing to an array, write to a new string instead. This is a different approach, but similar, to Rahul.menon's code. My approach may make more sense to you and it is well documented.

HI
deepak.hm123
the code will the desired output

void strev(char str[])
{
int I,len=strlen(str);//strlen give length of string
for(I=0;len=len-1; I>=len;I++;len--)
{
char temp;
temp=str[I];
str[I]=str[len];
str[len]=temp;
}
)

Edited 6 Years Ago by vijaykrishnabor: n/a

Comments
We do NOT give code to prople. That's cheating.

HI
deepak.hm123
the code will the desired output

void strev(char str[])
{
int I,len=strlen(str);//strlen give length of string
for(I=0;len=len-1; I>=len;I++;len--)
{
char temp;
temp=str[I];
str[I]=str[len];
str[len]=temp;
}
)

This doesnt work swapping wont do the job. if u input the "good boy" in str,
it would give "yobd oog".o/p must be "boy good" . this logic does not discriminate words. would work for singleword. for single word the logic using swap is

void strev(char str[])
{
int I,len=strlen(str);//strlen give length of string
int le = len;
char temp;
for(I=0,len=len-1; I<=le/2;I++,len--)
{
temp=str[I];
str[I]=str[len];
str[len]=temp;
}
printf("%s",str);
}

@vijaykrishnabor

All help is appreciated, but I agree that just giving out an answer is not constructive in this kind of forum. Also, you have way too many semicolons in that for loop. Finally, at least twice in this thread it has been mentioned that its the words that needs reversing, not the characters.


@deepak.hm123

Just curious if you ever got your problem solved?

This article has been dead for over six months. Start a new discussion instead.