0

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 by deepak.hm123: n/a

4
Contributors
11
Replies
13
Views
6 Years
Discussion Span
Last Post by N1GHTS
0
//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 by Rahul.menon: n/a

0

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

0

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.

0

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.

-1

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 by vijaykrishnabor: n/a

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

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);
}
0

@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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.