Welcome, %1$s. Please login or register.

February 21, 2018, 05:05:01 PM
: 1
: Reverse the words in a string  ( 2505 )
« : May 12, 2007, 12:30:56 AM From Shrinidhi»



Reverse the words in a string


How do you reverse the words in a string?

    "Software Engineers Of India"
                           to
    "India Of Engineers Software"

    An O(n) and 'in space' solution is expected.

 
Liked It? Share it!

              


« #1 : May 19, 2007, 12:03:26 AM From Poonam»

This one is simpler.. Just reverse each word and finally reverse the whole string. Thats it.
« #2 : May 31, 2007, 05:23:50 PM From iammilind»

Guru,
    It is easy to say the algo in English, but generally difficult to implement.

I have tried it here, it may not be perfect 0(n) but very optimized.
If in your compiler SPACE doesn't work then you can try using underscore '_' every where. This is according to unix compiler
===========================================================

#include<stdio.h>

#define SPACE ' '
#define SIZE 30

void Reverse_Words_of_String(char const str[])
{
        char *pTrav = (char*)str;
        char junk,*pPut_back = &junk;

        while(*(++pTrav))
                if(*pTrav == SPACE)
                        *pTrav = 0;

        while(pTrav-- != str)
                if(*pTrav == 0)
                {
                        printf("%s%c",pTrav+1,SPACE);
                        *pPut_back = SPACE;
                        pPut_back = pTrav;
                }
        printf("\n\n");
}

« #3 : June 27, 2007, 10:17:47 PM From forest.whisperz»

#include<stdio.h>
#include<stdlib.h>
void rev(char *,char *);
int main(void)
{
  char s[80],*start,*end,*tempend;
  int l;
  printf("enter the string\n");
  scanf("%[^\n]",s);
   start=end=tempend=s; 
   while(*end)
      end++;
  l=(end-start);
rev(start,end);

  while(l+1)
   {
     if(*tempend==' '||*tempend=='\0')
       {
         
         rev(start,tempend);
         start=(tempend+1);
       }
    tempend++;
     l--;
   }
printf("%s",s);
printf("\n");
return 0;
}

void rev(char *s,char *p)
 {
  char temp;
   p=p-1;
while(s<p)
      {   
          temp=*s;
          *s=*p;
          *p=temp;
         s++;
         p--;
       }
  }
 
: 1
« previous next »

 

Best RatedList All>>



Latest
Random



SMF 2.0.10 | SMF © 2015, Simple Machines | Contact Webmaster | OnlineFunDb.com © 2009/10 | Legal Disclaimer