GeekInterview.com
Series: Subject: Topic:
Question: 50 of 51

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"?

Asked by: monu2784 | Member Since May-2006 | Asked on: Jun 16th, 2006

View all questions by monu2784

Showing Answers 1 - 32 of 32 Answers
myidisid

Answered On : 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)

  
Login to rate this answer.
hemant.badhani

Answered On : Sep 13th, 2006

View all answers by hemant.badhani

#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

  
Login to rate this answer.
suchitra

Answered On : 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

  
Login to rate this answer.
hemant.badhani

Answered On : Sep 14th, 2006

View all answers by hemant.badhani

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

  
Login to rate this answer.
rajesh

Answered On : Sep 26th, 2006

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

  
Login to rate this answer.
Ramana Babu

Answered On : 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); 

}

  
Login to rate this answer.

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

Yes  1 User has rated as useful.
  
Login to rate this answer.

jus push the string into the stack and pop the stack once.

Yes  1 User has rated as useful.
  
Login to rate this answer.

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.....

  
Login to rate this answer.
Ravi

Answered On : 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 !

Yes  1 User has rated as useful.
  
Login to rate this answer.
Alice McGregor

Answered On : 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");}

  
Login to rate this answer.
anshuman sinha

Answered On : 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();  
        }

  
Login to rate this answer.
ILYAS

Answered On : 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();
        }
    }

Yes  1 User has rated as useful.
  
Login to rate this answer.
mo

Answered On : Apr 2nd, 2007

template
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(s,length);
cout << s<<endl;
int i = 0, j = -1;
for(;;)
{
while(j < length && s[++j] != ' ' );
reverseArr(s+i,j - i );
if(j >= length) break;
i = j+1;
}
return s;
}



  
Login to rate this answer.

      hai ramana,
i executed ur program it is not working,
the program reverse the character,

  
Login to rate this answer.
dhana

Answered On : 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)

  
Login to rate this answer.
Jayanth Saimani

Answered On : 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.

  
Login to rate this answer.
Sridhar

Answered On : 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;
}


  
Login to rate this answer.
Jhoga

Answered On : 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.

  
Login to rate this answer.
Raji

Answered On : Jul 3rd, 2007

hi

First reverse the entire sentence. then reverse every word

Raji

Yes  1 User has rated as useful.
  
Login to rate this answer.
orbimus

Answered On : 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;
}

  
Login to rate this answer.
sridhar surampudi

Answered On : 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.



  
Login to rate this answer.
Om Prakash

Answered On : 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

  
Login to rate this answer.
Alexander Higgins

Answered On : 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

  
Login to rate this answer.
prabhu

Answered On : Oct 13th, 2007

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

  
Login to rate this answer.
ritika

Answered On : 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

  
Login to rate this answer.
vosour

Answered On : Apr 13th, 2008

View all answers by vosour

C++, compiled by g++,

#include
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"

  
Login to rate this answer.
PDXTechie

Answered On : May 18th, 2008

View all answers by PDXTechie

In Perl it's easy -

print join ' ', reverse split /s/, 'This is a hat';

  
Login to rate this answer.
PDXTechie

Answered On : May 18th, 2008

View all answers by PDXTechie

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"

  
Login to rate this answer.
Amit Jain

Answered On : Jun 9th, 2011

View all answers by Amit Jain

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]='';
}
}
}

  
Login to rate this answer.
guest

Answered On : 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.  

  
Login to rate this answer.
maneesh

Answered On : 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.

  
Login to rate this answer.

Give your answer:

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

Related Open Questions

Ads

Connect

twitter fb Linkedin GPlus RSS

Ads

Interview Question

 Ask Interview Question?

 

Latest Questions

Ads

Interview & Career Tips

Get invaluable Interview and Career Tips delivered directly to your inbox. Get your news alert set up today, Once you confirm your Email subscription, you will be able to download Job Inteview Questions Ebook . Please contact me if you there is any issue with the download.