How do display the output as reverse of input, like input is "This is a hat" and the output should be "hat a is This"?

Questions by monu2784

Showing Answers 1 - 32 of 32 Answers

myidisid

  • Jul 3rd, 2006
 

There are two ways:

i) Create a temporary storage area and move to the end in the original string.Then pick a word from the right by moving left and encountering a space.and store these words in new array with a space appended.

ii)Reverse the string and then apply the same logic for each reversed word as you did for reversing the whole string.(this method is better as it does not require extra memory of order(n)

  Was this answer useful?  Yes

#include <stdio.h>

void main(int argc,char** argv[])
{
    int i;
    for(i=argc;i>1;i--)
    {
        printf("%s ",argv[i-1]);
    }
    printf("n");
}

cheers

hemant

  Was this answer useful?  Yes

suchitra

  • Sep 14th, 2006
 

respected sir,

i run ur program...

but i am to get the ans ...

please give advice how to run the program correctly..

thank you sir

urs truly

suchitra.A

  Was this answer useful?  Yes

Hi Sachitra,You need to give the string which is to be reversed as a command line argument.e.gif ur exe/binary name is "abc" thenif u type "abc Hello World" on the command prompt then u'll get "World Hello" as the outputcheersHemant

  Was this answer useful?  Yes

rajesh

  • Sep 26th, 2006
 

please send me the answer to make myself better in veifying my answer.

  Was this answer useful?  Yes

Ramana Babu

  • Dec 3rd, 2006
 

This is a simple program to reverse the string entered. The string will be reversed till enter key is pressed.

void main()
{
 
 char c;

 if((c = getchar()) != 'n')
 {
     main();
 }
  putchar(c); 

}

  Was this answer useful?  Yes

Here is a recursive version:
void reverse(char *str)
{
static int first_flag=1; // to take care of first word
if(strlen(str) == 0)
return;
char *word_boundary = NULL;
if(*str == ' ')
word_boundary = str + 1;
else if(first_flag == 1)
{
word_boundary = str;
first_flag = 0;
}
reverse(++str);
if(world_boundary != NULL)
while(world_boundary != ' ' || world_boundary != 'o')
printf("%c",*world_boundary++);
}
thanx

There are two ways to solve this problem......1. Make a linked list of all words that are in the string and then reverse the linked list.2. First reverse the string taking 'n' as delimeter and reverse it again taking ' ' space as argumentthanks n regards....rameshwar.....

  Was this answer useful?  Yes

Ravi

  • Feb 27th, 2007
 

Algorithm :
   1. reverse the original striing
   2. pick each word in the string and reverse each
      and you will get the result !

Alice McGregor

  • Mar 9th, 2007
 

I like my solution: chopping the original string. Only uses a single local variable as a pointer runner. This method isn't as creative as using separate arguments, but it does work with a wider range of test cases -- spaces at the beginning, end, and multiple spaces anywhere, all work as you would expect.#include #include int main(int *argc, char **argv) { char *p = argv[1]; /* Run through the array of characters, replacing spaces with NULLs. */ /* This effectively splits the string into substrings. */ for ( ; *p != 0; p++ ) if ( *p == ' ' ) *p = 0; /* Loop backwards through the allocated memory. */ /* Output any strings found, handling the first word of the argument. */ for ( p-- ; p >= argv[1]-1; p-- ) if ( *p == 0 || p < argv[1]) printf("%s ", p+1); printf("n");}

  Was this answer useful?  Yes

anshuman sinha

  • Mar 18th, 2007
 

see the c# code:
static void Main(string[] args)
        {
            string string1;
            int i = 0;
            string[] string3;
            Console.WriteLine("Input the string");
            string1 = Console.ReadLine();
            string1 = string1.Trim();
            char[] seperator = { ' ' };
            string3 = string1.Split(seperator);

            foreach(String string2 in string3)
            {
              
               i = i + 1;
            }
           
            for (int k = i-1; k >= 0; k--)
            {
                Console.Write("{0} ",string3[k]);
            }
            Console.ReadKey();  
        }

  Was this answer useful?  Yes

ILYAS

  • Mar 29th, 2007
 


C# code for this problem

class Program
    {
        static void Main(string[] args)
        {

            String []result;
            Console.Write("Please enter the string ");
            String inputString = Console.ReadLine();
           
            result= inputString.Split (' ') ;
            int siz = result .Length ;
            for (int i = siz-1; i >=0; i--) {

                Console.Write(result [i]);
                Console.Write(" ");
           
            }
            Console.Read();
        }
    }

mo

  • Apr 2nd, 2007
 

template<typename T>
void reverseArr(T* arr, int len)
{
T tmp;
int length = len-1;
for(int i=0; i<len/2; i++)
{
tmp = arr[i];
arr[i] = arr[length-i];
arr[length-i] = tmp;
}
}


char* reverseString(char* s)
{
int length = strlen(s);
reverseArr<char>(s,length);
cout << s<<endl;
int i = 0, j = -1;
for(;;)
{
while(j < length && s[++j] != ' ' );
reverseArr<char>(s+i,j - i );
if(j >= length) break;
i = j+1;
}
return s;
}



  Was this answer useful?  Yes

dhana

  • Apr 5th, 2007
 

hai ,
the program s

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[20];
scanf("%s",a);
if(strcmp(a,"n")==0)
return;
else
main();
printf("%s",a);
}

at the end of ur input u have to give n(space n)

  Was this answer useful?  Yes

Jayanth Saimani

  • May 24th, 2007
 

One thing you can do is save different strings as the nodes of the link list.
Meaning for eg. Jayanth is a programmer. First node jayanth. Second is ..and so on.
Then we just reverse the link list.

  Was this answer useful?  Yes

Sridhar

  • Jun 6th, 2007
 


I think using strstr( ) should make the program more readable.
I did not like playing with pointers (see below), but had no choice.

main()
{
 char *srcStr = "This is the string to be reversed";

 char destStr[100];

 int breakLoop = 0;

 char *p1, *p2; // traverse srcStr (front to back)
 char *d = destStr + strlen (srcStr); // traverse dest str (back to front)
 
 p1 = p2 = srcStr;

 *d-- = '';

 while (!breakLoop)
 {
          // grab word by word using p1 and p2
          p2 = strstr (p1, " ");

          if (p2 == NULL) // last word
          {
                   p2 = srcStr + strlen (srcStr);
                   breakLoop = 1;
          }

          // copy over this word to destination
          memcpy (d-(p2-p1)+1, p1, p2-p1);

          // Re-adjust pointers
          d = d-(p2-p1);
          *d-- = ' '; // Insert space
          p1 = p2+1;
 }


 cout << srcStr << endl;
 cout << destStr << endl;


 return 0;
}


  Was this answer useful?  Yes

Jhoga

  • Jun 18th, 2007
 

Easy way is to create an array, read the words of the line into the array.  Then recreate the string reading the array in reverse order.

  Was this answer useful?  Yes

Raji

  • Jul 3rd, 2007
 

hi

First reverse the entire sentence. then reverse every word

Raji

orbimus

  • Jul 8th, 2007
 

void reverse(char sz[], char* p, char* q) {
    char t, *s, *e;
    for(s=&p[0], e=&q[0]; e>=s ; ++s, --e) {
        t = *s;
        *s = *e;
        *e = t;
    }
}

int main() {
    char str[] = "Do or do not, there is no try.";
    size_t strLength = strlen(str);
    char *start, *end;
    for(start=&str[0], end=&str[0];
        *end != NULL;
        ++end)
    {
        if(*end == ' ' || *end == str[strLength-1]) {
            (*end == str[strLength-1])?
                reverse(str,start,end):
                reverse(str,start,end-1);
            start = end;
            ++start;
        }
    }
    reverse(str,&str[0],&str[strLength-1]);  
    return 0;
}

  Was this answer useful?  Yes

sridhar surampudi

  • Jul 22nd, 2007
 

Step 1:
Swap letters from left most with right most including spaces. Run this loop
till the middle of the sentence.
Ex : If original sentence is "Where is my hat"
Then after step 1 it will be "tah ym si erehW"


This can be done in O(n/2) where is n is the length of the sentence.


Step2:
In this step run a loop from the stating of modified string (string come after
step1)
If there is a space find in the sentence, take the string till the space
(exclude space)
and swap that word. Continue this till the end of the string.


Ex:
After step1 original string become "tah ym si erehW".
swap each word then the sentence will look like "hat my is Where".


The complexity of this algo is O(n).


Thanks.

  Was this answer useful?  Yes

Om Prakash

  • Aug 4th, 2007
 

Here is the code .....
you can copy this code and run it on TC..

#include<stdio.h>
#include<string.h>
#include<conio.h>

void main()
{
      clrscr();
      void reverse(char *,int);
       char *p,str[]="  THIS IS THE DOG";
 int k=0,flag=1;
 p=str;
 while(str[k++]!='')
 ;
 reverse(p,k);
}

void reverse(char *s, int l)
{       char *t;t=s;
 int i=0,flag=1;
 while(*s!='')
 {    --l;
 if(*s == ' '|| *s == 't')
 {
  if(flag == 0)
  {
   *s='';
   flag=1;
   reverse(s+1,l);

  }
 }
 else
 flag=0;
 s++;
 }
       if(l>=1)
       printf("%s ",t);
}



Output will be :-    DOG THE IS THIS

  Was this answer useful?  Yes

Alexander Higgins

  • Sep 18th, 2007
 

Ok, here's a simple way to do it.
Function ReverseWords(ByVal text As String)
Dim s() As String = Split(text, " ") : text = ""
For i As Integer = s.Length - 1 To 0 Step -1
text &= s(i) & " "
Next
Return text
End Function

  Was this answer useful?  Yes

prabhu

  • Oct 13th, 2007
 

void main()
{
      char c[100];
      int i;;
      for(i=strlen(gets(c));i>=0;i--)
      {
                printf("%c",c[i]);
      }
}

  Was this answer useful?  Yes

ritika

  • Oct 22nd, 2007
 

In VB.Net:
If we take two textboxes. In first we put the string and in other we display the
reverse...
on TextBox1_MouseClick event:
Dim i As Integer = 0
Dim limit As Integer
limit = Me.TextBox1.Text.LengthWhile i < limit
i = i + 1
Me.TextBox2.Text += Me.TextBox1.Text.Chars(limit - i)
End While

  Was this answer useful?  Yes

vosour

  • Apr 13th, 2008
 

C++, compiled by g++,

#include <string>
using namespace std;

string revSentence( const string & s ) {
  int x = s.find(' ');
  if (x != string::npos)
    return revSentence(s.substr(x+1)) + " " + s.substr( 0, x );
  else
    return s;
};

main() {
  string test = "This is a hat";
  cout << "Input  : "" << test << """ << endl;
  cout << "Output : "" << revSentence(test) << """ << endl;
}


Input  : "This is a hat"
Output : "hat a is This"

  Was this answer useful?  Yes

PDXTechie

  • May 18th, 2008
 

The forum filtered the output ... between the slashes should be "backslash s" ...

If you wanted to reverse the whole string, btw, just split on nothing --

print reverse split //, "This is a hat";

Will print "tah a si sihT"

  Was this answer useful?  Yes

Amit Jain

  • Jun 9th, 2011
 

void f(char *str) {
int l=strlen(str);
int i=l-1;
int temp=-1;
while(i>=0){
while(str[i]!=' '&& i!=0){
i--;
}
printf("%s ",str+i+(i==0?0:1));
if(temp!=-1){
str[temp]=' ';
}
temp=i--;
if(i>0){
str[temp]='';
}
}
}

  Was this answer useful?  Yes

guest

  • Aug 5th, 2011
 

#This is why Perl Rocks!

Code
  1. #!/usr/bin/perl

  2.  

  3.  

  4. print "Enter String:

  5. ";

  6.   my $input;

  7.   chop($input = <STDIN>);

  8.  

  9.   my $revers = reverse $input;

  10.   print "$revers

  11. ";

  12.  

  Was this answer useful?  Yes

maneesh

  • Aug 8th, 2011
 

Push the characters onto a stack and then pop every1. Or get the string length and then iterate backwards from the last character.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions