Reverse words in a given string

Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”

Algorithm:

1) Reverse the individual words, we get the below string.
     "i ekil siht margorp yrev hcum"
2) Reverse the whole string from start to end and you get the desired output.
     "much very program this like i"
#include<stdio.h>

/* function prototype for utility function to
  reverse a string from begin to end  */
void reverse(char *begin, char *end);

/*Function to reverse words*/
void reverseWords(char *s)
{
  char *word_begin = s;
  char *temp = s; /* temp is for word boundry */

  /*STEP 1 of the above algorithm */
  while( *temp )
  {
    temp++;
    if (*temp == '\0')
    {
      reverse(word_begin, temp-1);
    }
    else if(*temp == ' ')
    {
      reverse(word_begin, temp-1);
      word_begin = temp+1;
    }
  } /* End of while */

   /*STEP 2 of the above algorithm */
  reverse(s, temp-1);
}

/* UTILITY FUNCTIONS */
/*Function to reverse any sequence starting with pointer
  begin and ending with pointer end  */
void reverse(char *begin, char *end)
{
  char temp;
  while (begin < end)
  {
    temp = *begin;
    *begin++ = *end;
    *end-- = temp;
  }
}

/* Driver function to test above functions */
int main()
{
  char s[] = "i like this program very much";
  char *temp = s;
  reverseWords(s);
  printf("%s", s);
  getchar();
  return 0;
}

The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple space in between. Thanks to rka143 for providing this version.

void reverseWords(char *s)
{
    char *word_begin = NULL;
    char *temp = s; /* temp is for word boundry */

    /*STEP 1 of the above algorithm */
    while( *temp )
    {
        /*This condition is to make sure that the string start with
          valid character (not space) only*/
        if (( word_begin == NULL ) && (*temp != ' ') )
        {
            word_begin=temp;
        }
        if(word_begin && ((*(temp+1) == ' ') || (*(temp+1) == '\0')))
        {
            reverse(word_begin, temp);
            word_begin = NULL;
        }
        temp++;
    } /* End of while */

    /*STEP 2 of the above algorithm */
    reverse(s, temp-1);
}

Time Complexity: O(n)

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.





  • Abhishek Kumar

    can we do like this..??
    1)first store d whole string in an stack..
    2)after that pop the words from stack nd wenever we meet with space we just reverse the given chars..

  • VaraKalyan M

    Can be solved easily using stack in 0(n)

  • poorvisha

    .if i/p is :mynamekhan

    o/p will be:khannamemy , according to the above given program.

    but o/p should be :khannamemy.

    am i correct? the above case is not handled.

  • Danie

    string reversing in java :

    kodingexamples.blogspot.com/2014/04/how-to-reverse-string-in-java.html

  • http://iammukesh.info Mukesh Sharma

    public static String reverseWords(String s)
    {
    String str=””;
    String fin=””;

    for(int i=s.length()-1;i>=0;i–)

    {

    str=str+s.charAt(i);

    }

    int beg=0;

    for(int i=0;i=beg;j–)

    {

    fin=fin+str.charAt(j);

    }

    beg=i+1;

    fin=fin+” “;

    }

    else if((str.charAt(i)!=’ ‘)&&(i==str.length()-1))

    {

    for(int j=i;j>=beg;j–)

    {

    fin=fin+str.charAt(j);

    }

    beg=i+1;

    }

    }

    return fin;

    }

  • pavansrinivas

    How can I reduce my space complexity??

    void reverseWords(){
    String a = "a efgh klmnop";
    String res = "";
    String res2 = "";
    int i =0;
    while(i<a.length()){
    int j = i;
    while(i=j){
    res = res+a.charAt(k);
    k--;
    }
    res = res+" ";
    i++;
    }
    for(int l=a.length()-1;l>=0;l--){
    res2+=res.charAt(l);
    }
    System.out.print(res2);
    }

  • Iamateur

    Hey somebody please give me the right program for this..So many replies which one is correct?

    • Charm03

      I agree, someone please rate which one is most optimal and correct answer to this question?

  • surbhi

    #include
    int main()
    {

    char s[100],s1[100];
    int i,j=0,l=0;
    printf(“enter any string\n”);
    fgets(s,100,stdin);

    for(i=0;s[i]!=’\0′;i++)
    l++;

    for(i=l;i>=0;i–)
    s1[j++]=s[i];

    s1[j]=’\0′;
    printf(“string is \n”:);
    fputs(s1,stdout);

    return 0;
    }

  • Karan
     
    # include <stdio.h>
    # include <stdlib.h>
    
    
    void push( char stack[], char c,int* top,int len )
    {
            if((*top) == len)
                return;
            stack[(*top)++]=c;
    }
    
    char pop( char stack[],int* top )
    {
        (*top)--;
        return stack[*top];
    }
    
    
    void rev(char *str)
    {
        int len=strlen(str);
        char *stack=malloc(len*sizeof(char));
        int i=0;
        int top=0;
        int j=0;
        while(*(str+i))
        {
            push(stack,*(str+i),&top,len);
            i++;
        }
        i=0;
    
        while(top!=-1 && *(str+i))
        {
          if(top!=-1){
          *(str+i)=pop(stack,&top);
            i++;
          }
    
        }
    
        i=0;
    
        while(*(str+i))
        {
            if(top==-1 && *(str+i)==' '){
                i++;
                continue;
            }
            else
            {
    
                if(*(str+i)!=' ')
                {
                    push(stack,*(str+i),&top,len);
                    i++;
                }
    
                else
                {
                    i++;
                     while(*(str+j)!=' ')
                    {
                        if(top!=-1){
                        *(str+j)=pop(stack,&top);
                         j++;
                        }
                    }
                    j++;
    
                }
    
            }
    
        }
        printf("%s",str);
    
    }
    int main()
    {
      char s[] = " i like this program very much ";
      rev(s);
      return 0;
    }
    
     

    This will handle the case when string starts with spaces.

  • Karan
     
     # include <stdio.h>
    # include <stdlib.h>
    
    
    void push( char stack[], char c,int* top,int len )
    {
            if((*top) == len)
                return;
            stack[(*top)++]=c;
    }
    
    char pop( char stack[],int* top )
    {
        (*top)--;
        return stack[*top];
    }
    
    
    void rev(char *str)
    {
        int len=strlen(str);
        char *stack=malloc(len*sizeof(char));
        int i=0;
        int top=0;
        int j=0;
        while(*(str+i))
        {
            push(stack,*(str+i),&top,len);
            i++;
        }
        i=0;
    
        while(top!=-1 && *(str+i))
        {
          if(top!=-1){
          *(str+i)=pop(stack,&top);
            i++;
          }
    
        }
    
        i=0;
    
        while(*(str+i))
        {
            if(top==-1 && *(str+i)==' '){
                i++;
                continue;
            }
            else
            {
    
                if(*(str+i)!=' ')
                {
                    push(stack,*(str+i),&top,len);
                    i++;
                }
    
                else
                {
                    i++;
                     while(*(str+j)!=' ')
                    {
                        if(top!=-1){
                        *(str+j)=pop(stack,&top);
                         j++;
                        }
                    }
                    j++;
    
                }
    
            }
    
        }
        printf("%s",str);
    
    }
    int main()
    {
      char s[] = " i like this program very much ";
      rev(s);
      return 0;
    }
    */
     

    This will handle the cases when the string starts with space.

  • Vignesh

    # include
    # include
    void strnrev(char *s,int n)
    {
    if(n < 0)
    return;
    printf("%c",s[n]);
    strnrev(s,n-1);
    }

    int main()
    {
    char s[50];
    gets(s);
    strnrev(s,strlen(s)-1);
    getch();
    }

  • ritesh

    Reversing words in a string.
    #include
    #include “conio.h”

    using namespace std;

    void reverse_string( char * beg,char * end)
    {
    while((beg<end))
    { char temp=*beg;
    *beg=*end;
    *end=temp;
    beg++;end–;
    }
    }
    void reverse_string_word(char *str)
    { char *beg1=str;
    char *end1=str;
    while(*end1)
    {end1++;
    if(*end1=='')
    reverse_string(beg1,end1-1);
    else if(*end1==' ')
    {reverse_string(beg1,end1-1);
    beg1=end1+1;
    }
    }
    reverse_string(str,end1-1);
    }
    //Driver program
    int main()
    { char string[]="ritesh is my name";
    char * str=string;
    for (int i=0;i<strlen(str);i++)
    cout<<*(str+i);
    cout<<endl;
    reverse_string_word(str);
    int ka=strlen(str);
    for (int i=0;i<strlen(str);i++)
    cout<<*(str+i);
    cout<<endl;
    cout<<str;
    getch();
    return 0;
    }

    /* Paste your code here (You may delete these lines if not writing code) */

  • aspire

    @GeeksforGeeks : The complexity of the above code looks like O(n2) because after you traverse a word you are traversing it again for reversing purpose. Please look into this.

  • pratul

    The code I’ve written below is pretty basic and not much complicated !!! …

    #include
    #include
    void fun(char a[])
    {
    int k,j,l=strlen(a),p=l;
    for(k=l-1;k>=0;k–)
    {
    if(a[k]==32 || k==0)
    {
    j=(k==0)?0:k+1;
    for(;j<p;j++)
    printf("%c",a[j]);

    printf(" ");
    p=k;
    }
    }
    }
    int main()
    {
    char str[] = "i am a good boy";
    fun(str);
    return 0;
    }

    • raghavendar

      pratul please give me explanation for your prigram

      • pratul

        Hi… what I’m doing in my code is that I’m scanning the whole string from right to left and whenever I encounter a space (or the string reaches its starting)..I reverse the word just after the space.

        For this purpose,I have maintained a variable ‘p’ which is updated to the new end point for reversing purpose.

        Just go through the code once…u’ll get to know how it actually works…

         
        /* Paste your code here (You may delete these lines if not writing code) */
         
  • Aditya Ambashtha

    This is compact and works well i guess…

     
    void printReverse(char *str)
    {
        char temp[10];
        int cnt;
    
        for(cnt=0;(str[cnt]!=' ')&&(str[cnt]!='\0');cnt++)
            temp[cnt]=str[cnt];
    
    
        temp[cnt]='\0';
    
    
        if (str[cnt]!='\0')
            printReverse(&str[cnt+1]);
    
        printf("%s ",temp);
    }
     
  • Prateek Sharma

    Python code with o(n) time and o(1) space complexity…

    def swap(list1,j,i):
    if j >= i:
    return 0
    else:
    temp = list1[j]
    list1[j] = list1[i]
    list1[i] = temp
    swap(list1,j+1,i-1)
    def reverseStringWordsPosition(s):
    list1 = list(s)
    j =0
    for i in range(len(list1)):
    if list1[i] !=" ":
    continue
    elif i ==0 or list1[i-1] == " " :
    j =j+1
    else:
    swap(list1,j,i-1)
    j =i+1
    if list1[-1] != " ":
    swap(list1,j,i)
    print "".join(list1)
    swap(list1,0,len(list1)-1)
    print "".join(list1)

    def main():
    string = " hi how ru "
    reverseStringWordsPosition(string)

    if __name__ == ‘__main__':
    main()

  • abhishek08aug
     
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    void reverse_string(char * start, char * end) {
      char * temp=(char *)malloc(sizeof(char));
      while(start<end) {
        *temp=*start;
        *start=*end;
        *end=*temp;
        start++;
        end--;
      }
    }
    
    void reverse_words(char * str) {
      char * word_start=str;
      if(word_start==NULL) {
        return;
      }
      char * temp=str;
      while(*temp!='\0') {
        temp++;
        if(*temp==' ') {
            reverse_string(word_start, temp-1);
            word_start=temp+1;
        } else if (*temp=='\0'){
            reverse_string(word_start, temp-1);
        }
      }
    }
      
    int main() {
      char * str=(char *)malloc(sizeof(char)*40);
      strcpy(str, "you like this program very much");
      reverse_words(str);
      printf("String after reversing words is: %s\n", str);
      return 0;
    }
     

    String after reversing words is: uoy ekil siht margorp yrev hcum

    • abhishek08aug

      #include
      #include
      #include

      void reverse_string(char * start, char * end) {
      char * temp=(char *)malloc(sizeof(char));
      while(start *temp=*start;
      *start=*end;
      *end=*temp;
      start++;
      end–;
      }
      }

      void reverse_words(char * str) {
      char * word_start=str;
      if(word_start==NULL) {
      return;
      }
      char * temp=str;
      while(*temp!=’\0′) {
      temp++;
      if(*temp==’ ‘) {
      reverse_string(word_start, temp-1);
      word_start=temp+1;
      } else if (*temp==’\0′){
      reverse_string(word_start, temp-1);
      }
      }
      reverse_string(str, temp-1);
      }

      int main() {
      char * str=(char *)malloc(sizeof(char)*40);
      strcpy(str, “you like this program very much”);
      reverse_words(str);
      printf(“String after reversing words is: %s\n”, str);
      return 0;
      }

      String after reversing words is: much very program this like you

  • pranav
     
    
    void reverse(char s[],int low,int high)
    {
            int i,j;
            int temp;
    
            for (i=low,j=high;i<j;i++,j--)
            {
                    temp = s[i];
                    s[i] = s[j];
                    s[j] = temp;
            }
    }
    
    #define DELIM 1
    #define NO_DELIM 0
    
    void reverseWords(char s[])
    {
            int i,j;
            int last_char = NO_DELIM;
            int delim_count=0;
    
            reverse(s,0,strlen(s)-1);
    
            for(i=0,j=0;s[i]!='\0';i++)
            {
                    if (s[i]!=' ' && s[i]!='\t' && s[i]!='\n')
                    {
                            if (last_char == DELIM)
                            {
                                    reverse(s,j,i-delim_count-1);
                                    last_char = NO_DELIM;
                                    delim_count = 0;
                                    j = i;
                            }
                    }
                    else {
                            last_char = DELIM;
                            delim_count++;
                    }
            }
    
            reverse(s,j,i-delim_count-1);
    }
    
     
  • Star_Trek

    reverse_words_in_a_string(string,stlength)
    {
    for(start=end=0;end<stlength;end++)
    {
    if(string[end]!='')
    {
    start=end;
    while(string[end]!='' && end<stlength)
    {
    end++;
    }
    end–;
    reverseword(string,start,end);
    }
    }
    }

    reverse string(string,strstart,strend)
    {
    for(char temp;start<end;start++,end–)
    {
    temp=string[start];
    string[start]=str[end];
    str[end]=temp;
    }

    }

    /* Paste your code here (You may delete these lines if not writing code) */

  • RGUIIIT
     
    #include<stdio.h>
    #include<string.h>
    main()
    {
          char *pch;
          char str[]= "This is a sample string.";
          printf("Reversing the sentence \"%s\"\n",str);
          pch = strtok(str,"\n");
          
          while(pch != NULL)
          {
                    strrev(pch);
                    printf("\n%s\n",pch);                
                    pch = strtok(NULL, "\n");
          }
          getch();
    }
     
  • anand

    /* private static String reverseAText(String s) {
    String[] sarray = s.split(" ");
    return reverseAText(sarray, 0 , sarray.length – 1);
    }

    private static String reverseAText(String[] s,int i ,int n) {
    if(i == n)
    return s[n];
    else{
    return reverseAText(s, i+1, n)+" "+s[i];
    }
    } */

  • Gangadhara
     
    
    #include<stdio.h>
    #include<string.h>
    char str[]="I love india";
    void Reverse(char *revStr)
    {
    	if(!revStr)return;
    	Reverse(strtok(NULL," "));
    	printf("%s ",revStr);
    }
    int main()
    {
    	Reverse(strtok(str," "));
    	return 0;
    }
     
  • Gangadhara

    #include
    #include
    char str[]=”I love india”;
    void Reverse(char *revStr)
    {
    if(!revStr)return;
    Reverse(strtok(NULL,” “));
    printf(“%s “,revStr);
    }
    int main()
    {
    Reverse(strtok(str,” “));
    return 0;
    }

    • Vibhu Tiwari

      great solution man..

    • Marsha Donna

      can u pls explain wat does Reverse(strtok(NULL,” “)); do??

  • sush

    Simple and easy implementation

     
    #include<stdio.h>
    #include<stdlib.h>
     #include<string.h>
    /*Function to reverse words*/
    void reverse(char* str,int l,int h)
    {
        if(l<=h)
    	{
    		char temp=str[l];
    		str[l]=str[h];
    		str[h]=temp;
    		reverse(str,l+1,h-1);
    	}
    }
    void reverse_words(char* s)
    {
    	int i=0,len=strlen(s),l,h;
    	while(i<len)
    	{
    		while(s[i]==' ')
    		++i;
    		if(i>=len)
    		break;
    		l=i;
    		while(s[i] && s[i]!=' ')
    		++i;
    		h=i-1;
    		reverse(s,l,h);
    	}
    	reverse(s,0,len-1);
    }
     
    /* Driver function to test above functions */
    int main()
    {
      char s[] = "i like this program very much";
      reverse_words(s);
      printf("%s", s);
      getchar();
      return 0;
    }   
     
  • datta

    /*You can also tokenize the given string using strtok() and get the string reversed in the terms of words sequence*/

    #include
    #include
    #include
    #include

    void rev(char *start,char *end);
    void reverse_whole(char *str);
    int main()
    {
    char *str;
    str = malloc(sizeof(char *));

    printf(“Enter the string:\n”);//Suppose the input is”my name is datta”
    // gets(str);
    scanf(“%[^\n]”,str);
    reverse_whole(str);

    printf(“The reversed string is %s\n”,str);//The output will be “datta is name my”
    return 1;
    }

    void reverse_whole(char *str)
    {
    char *tmp,*start;

    tmp = str;
    start = str;

    while(*tmp){
    tmp++;
    if(*tmp == ”){
    rev(start,tmp-1);
    }
    if(*tmp == ‘ ‘){
    rev(start,tmp -1);
    start = tmp+1;
    }
    }
    rev(str,strlen(str)+str-1);

    return ;
    }

    void rev(char *start,char *end)
    {
    char tmp;

    while(start < end){
    tmp = *end;
    *end = *start;
    *start = tmp;
    start++;end–;
    }
    return ;
    }

  • pr6989
     
    //Reverse the words of a string in place
    #include<iostream>
    #include<string.h>
    #define max 100
    using namespace std;
    void swap(char*,char*);
    int main()
    {
        char a[max];
        cout<<"Enter a string : ";
        cin.getline(a,max);
        int i,j,k;
        int count_blanks=0;
        for(i=0;a[i]!='\0';i++)
        {
            if(a[i]==' ')
            count_blanks++;
        }
        //first reverse the whole string in place
        for(i=0,j=strlen(a)-1;i<j;i++,j--)
        {
            swap(&a[i],&a[j]);
        }
        //now reverse each word in place
        if(count_blanks>0)    //more than one word in string
        {
                i=0;
                j=0;
                do
                {
                    while(a[j+1]!=' '&&a[j+1]!='\0')
                    j++;
                    if(j!=strlen(a)-1)
                    k=j+2;
                    else
                    k=j+1;
                    for(;i<j;i++,j--)
                    {
                    swap(&a[i],&a[j]);
                    }
                    if(a[k]!='\0')
                    {
                        i=k;
                        j=k;
                    }
                    else
                    break;
                }while(a[k]!='\0');
        }
        cout<<"Reversed string : "<<a<<endl;
        return 0;
    }
    void swap(char*a,char*b)
    {
        char t;
        t=*a;
        *a=*b;
        *b=t;
    }
    
     
  • bhavesh
     
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    int main()
    {
    	char str[]="my  name is bhavesh";
    	struct node{
    	char  *a;
    	struct node *next;
    	};
    	char *ab;
    	struct node *head=(struct node*)malloc (sizeof(struct node));
    	ab=strtok(str , " ");
    		char *abc=(char *)malloc (sizeof (char)*90);
    		strcpy(abc,ab);
    		head->a = abc;
    		head->next=NULL;
    	while((ab=strtok(NULL , " "))!=NULL)
    	{
    		struct node *temp=(struct node*)malloc (sizeof(struct node));
    		char *abc=(char *)malloc (sizeof (char)*strlen(ab));
    		strcpy(abc,ab);
    		temp->a = abc;
    		temp->next=head;
    		head=temp;
    	}
    	while(head)
    	{
    		printf("%s  ",head->a);
    		head=head->next;
    	}
    		printf("\n");
    	
    	return 0;
    }
    		 
  • Geek1

    Made some changes, like passing temp+1 to reverse, this is a working code.

     
    #include "StdAfx.h"
    #include "conio.h"
    #include "iostream"
    #include "string"
    #include "math.h"
    using namespace std;
    void reverseWords(char *s)
    {
    	char *word_begin = NULL;
    	char *temp = s; /* temp is for word boundry */
     
    	/*STEP 1 of the above algorithm */
    	while( *temp )
    	{
    		/*This condition is to make sure that the string start with
    			valid character (not space) only*/
    		if (( word_begin == NULL ) && (*temp != ' ') )
    		{
    			word_begin=temp;
    		}
    		if(word_begin && ((*(temp+1) == ' ') || (*(temp+1) == '\0')))
    		{
    			reverse(word_begin, temp+1);
    			word_begin = NULL;
    		}
    		temp++;
    	} /* End of while */
     
    	/*STEP 2 of the above algorithm */
    	reverse(s, temp);
    }
    
    void reverse (char *start, char *end)
    {
    	char *temp;
    	while(start<end)
    	{
    		*temp = *start;
    		*start++= *end;
    		*end--= *start;
    	}
    }
    
    int main()
    {
    char s[] ="    This is a playground   which is very big       ";
    char *temp =s;
    reverseWords(s);
    printf("%s", s);
    _getch();
    return 0;
    }
    
     
  • Geek1

    This one is a working code which would cater the spaces as well, done some modification in the actual code, just some temp+1 is now being passed to the reverse.

     
    #include "StdAfx.h"
    #include "conio.h"
    #include "iostream"
    #include "string"
    #include "math.h"
    using namespace std;
    void reverseWords(char *s)
    {
        char *word_begin = NULL;
        char *temp = s; /* temp is for word boundry */
     
        /*STEP 1 of the above algorithm */
        while( *temp )
        {
            /*This condition is to make sure that the string start with
              valid character (not space) only*/
            if (( word_begin == NULL ) && (*temp != ' ') )
            {
                word_begin=temp;
            }
            if(word_begin && ((*(temp+1) == ' ') || (*(temp+1) == '\0')))
            {
                reverse(word_begin, temp+1);
                word_begin = NULL;
            }
            temp++;
        } /* End of while */
     
        /*STEP 2 of the above algorithm */
        reverse(s, temp);
    }
    
    void reverse (char *start, char *end)
    {
    	char *temp;
    	while(start<end)
    	{
    		*temp = *start;
    		*start++= *end;
    		*end--= *start;
    	}
    }
    
    int main()
    {
    char s[] ="    This is a playground   which is very big       ";
    char *temp =s;
    reverseWords(s);
    printf("%s", s);
    _getch();
    return 0;
    }
    
     
  • Avinash
     
    Reverse Words in a sentence
    
    void ReverseWords(char *str)
    {
    	int wordstart=0, wordend=0;
    	int len= strlen(str);
    	ReverseString(str,0, len-1)
    	
    	for(wordend=0;wordend<len;wordend++)
    	{
    		If(str[wordend]!='')
    		{
    			wordstart=wordend;
    			while(str[wordend]!=''&&wordend<len)
    			{
    				wordend++;
    			}
    			wordend--;
    			ReverseString(str,wordstart, wordend);
    		}
    	}
    }
    
    ReverseString(char *str, int start, int end)
    {
    	char *temp;
    	while(start<end)
    	{
    		temp=str[start];
    		str[start]=str[end];
    		str[end]=temp;
    	}
    }
     
  • http://mobilityworld.wordpress.com/ Punit

    Following is an implementation in Java using StringBuilder..

    public class REVERSEWORDS {
    public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("GEEKS FOR HELP");
    System.out.println(sb.toString());
    reverseWords(sb);
    System.out.println(sb.toString());
    }

    private static void reverseWords(StringBuilder sb) {
    //Step 1 : Reverse individual words
    short start_word = 0;
    for(int i=0;i<sb.length();i++){
    if(sb.charAt(i)==’ ‘){
    reverseWord(sb, start_word, i-1);
    start_word = (short) (i+1);
    }else if(i == sb.length()-1){
    reverseWord(sb, start_word, i);
    }
    }
    reverseWord(sb, (short) 0, sb.length()-1);
    }

    private static void reverseWord(StringBuilder sb, short start_word, int end_word) {
    while(start_word < end_word){
    char temp = sb.charAt(start_word);
    sb.setCharAt(start_word, sb.charAt(end_word));
    sb.setCharAt(end_word, temp);
    start_word++;
    end_word–;
    }
    }
    }

  • Saurya

    Please comment on my implementation.

     
    /* Paste your code here (You may delete these lines if not writing code) */
    /*Reverse the words in a string*/
    #include <iostream>
    #include <stack>
    using namespace std;
    int main()
    {
      stack<char> wrd;
      char ar[] =  {"i ekil siht margorp yrev hcum"};
      int i = 0, j=0;
      while(ar[i]!='\0')
      {
        wrd.push(ar[i]);
        i++;
      }
      i=0;
      while(!wrd.empty())
      {
        ar[i] = wrd.top();
        wrd.pop();
        i++;
      }
      puts(ar);
      return 0;
    }
    
    
     
    • http://dealsindiadeals.com topcoder

      Using in-built stack is not allowed in PI’s

  • Anonymous

    In case of java, we can do this:
    1) Use StringTokenizer to separate the words
    2) Push each token into to a stack
    3) Pop them out

  • CaesiumX

    Hello geeks team
    what about this ->

      

    #include<stdio.h>
    #include<conio.h>
    #include<string.h>
    void reverse(char str[])
    {
    char *beg=str;
    char *end=str+strlen(str)-1;
    char temp=NULL;
    while(beg<end)
    {
    temp=*beg;
    *beg=*end;
    *end=temp;
    beg++;
    end–;
    }
    }

    void main()
    {
    char str[]="i like this program very much";
    char a[50][50];
    char *res=NULL;
    char delim[]=" ";
    int i=1,j=2; //i->counter for storing the atrget string , j will keep on adding the reversed strings to i
    clrscr();
    strcpy(a[0],str);
    reverse(a[0]);
    res=strtok(a[0],delim); //to check for the delimeter ‘ ‘ to seperate strings and storing them further to a[]
    while(res!=NULL)
    {
    strcpy(a[i],res);
    i++;
    res=strtok(NULL,delim);
    }
    reverse(a[1]);
    //this condition after a[1] will append all upcoming string seperated to one concatenated string a[1]
    while(j<=i)
    {
    reverse(a[j]);
    strcat(a[1]," ");
    strcat(a[1],a[j]);
    j++;
    }
    printf("%s\n",a[1]);
    getch();
    }

    • CaesiumX

      @geeksforgeek guys a nice portal like this shouldn’t dawdle , on both forums and portal channelling different web pages takes a hell lot of time , i know a lot process operations/interceptions are involved in back end while n number of users post/code simultaneously but i have seen this even when there is no traffic which is not good considering the type of members we have here.

      • http://geeksforgeeks.org/ Sandeep

        @CaesiumX: The site is currently hosted on a shared web server. The site has become slow due to increase in traffic. We will soon be migrating the site to a dedicated server.

  • amit khoth

    @geeksforgeeks correct this code.for same type of word it is not working.

    • GeeksforGeeks

      @amit khoth: Could you please provide a sample string for which it didn’t work?

  • Sunil

    Check this program. You can easily reverse all the words in the sentence.

     
    #include<stdio.h>
    #include <string.h>
    
    int main()
    {
    	char *sentence="This website is awesome";
    	char *words[50];
    	char *temp;
    	int i,j;
    	
    	temp=strtok(sentence," ");
    	for(i=0;temp!=NULL;i++)
    	{
    		words[i]=temp;
    		temp=strtok(NULL," ");
    	}
    	
    	for(j=0;j<i;j++)
    	{
    		printf("%s\n",words[j]);
    	}
    	
    	return 0;
    }
     
    • ramesh

      it shows Run time error in Devcpp…

      • Sunil bn

        I dint get any such error. I used borland compiler and its working fine :)

      • http://geeksforgeeks.org/?page_id=2 Venki

        Change the following statement

        char *sentence=”This website is awesome”;

        to

        char sentence[] = “This website is awesome”;

        or

        static char sentence[] =”This website is awesome”;

        Borland compiler placing string literals in modifiable memory.

        • ramesh

          yep thank u…

          char sentence[] = “This website is awesome”;
          works…

          but to print in reverse…

          int main()
          {
          static char sentence[]=”This website is awesome”;
          char *words[50];
          char *temp;
          int i,j;

          temp=strtok(sentence,” “);
          for(i=0;temp!=NULL;i++)
          {
          words[i]=temp;
          temp=strtok(NULL,” “);
          }

          for(j=i;j>=0;j–)
          {
          printf(“%s\n”,words[j]);
          }
          getch();
          return 0;
          }

  • yeskay
     // To reverse the words in a sentence...
    #include<stdio.h>
    #include<string.h>
    void swap(char *a,char *b){
            char temp = *a;
            *a = *b;
            *b = temp;
    }
    
    void toReverseWords(char *str,int len){
            int i=0,j=0,next=0;
    
            for(i=0;i<len;i=j=next){
                    for(j=i;str[j+1]!=' ' && str[j+1]!='\0' && j<len;j++);
    
                    next=j+2;
    
                    while(j<len && i<j){
                            swap(&str[i],&str[j]);
                            i++;j--;
                    }
    }
            for(i=0,j=(len-1);i<(len/2) &&  i<j;i++,j--)
                    swap(&str[i],&str[j]);
    }
    
    int main(){
            char str[]="hi this is giri from 09mx";
            int len=strlen(str);
            printf("%s\n",str);
            toReverseWords(str,len);
            printf("%s\n",str);
    return 0;
    }
    
     
  • http://ashutosh7s.blogspot.com/ wgpshashank

    we have this string s1 = “My name is X Y Z” and I want to reverse the order of the words so that s1 = “Z Y X is name My”.

     
       static char[] ReverseAllWords(char[] in_text)
        {
            int lindex = 0;
            int rindex = in_text.Length - 1;
            if (rindex > 1)
            {
                //reverse complete phrase
                in_text = ReverseString(in_text, 0, rindex);
    
                //reverse each word in resultant reversed phrase
                for (rindex = 0; rindex <= in_text.Length; rindex++)
                {
                    if (rindex == in_text.Length || in_text[rindex] == ' ')
                    {
                        in_text = ReverseString(in_text, lindex, rindex - 1);
                        lindex = rindex + 1;
                    }
                }
            }
            return in_text;
        }
    
        static char[] ReverseString(char[] intext, int lindex, int rindex)
        {
            char tempc;
            while (lindex < rindex)
            {
                tempc = intext[lindex];
                intext[lindex++] = intext[rindex];
                intext[rindex--] = tempc;
            }
            return intext;
        }
     

    Correct me if i missed sumthing

    • http://ashutosh7s.blogspot.com/ wgpshashank
       
      #include<iostream>
       
      using namespace std;
       
      void str_rev(char s[], int start, int end)
      {
              int len = end - start;
              for(int i=0;i<len/2;i++)
              {
                      char t = s[i+start];
                      s[i+start] = s[end-i-1];
                      s[end-i-1] = t;
              }
      }
       
      int main()
      {
              char a[] = "my name is prabhu";
              cout << "[" << a < ";
       
              str_rev(a,0,strlen(a));
       
              int start_index = 0;
              for(size_t i=0;i<=strlen(a);i++)
              {
                      if(a[i] == ' ' || a[i] == '')
                      {
                              str_rev(a,start_index,i);
                              start_index = i+1;
                      }
              }
              cout << "[" << a << "]" << endl;
      }
       
    • http://ashutosh7s.blogspot.com/ wgpshashank
    • Nebula

      ///Include string.h This is my version
      #define kcSPACE ‘ ‘
      #define ksSPACE ” ‘
      #define kMAX_STRING 128

      void _ReverseWordOrder(char *const lacString){

      char *ptr_lacString;
      char *ptr_lacWord;
      char lacAux[kMAX_STRING]={NULL};

      ptr_lacWord=strrchr(lacString,kcSPACE);

      while(NULL!=ptr_lacWord){
      strcat(lacAux,ptr_lacWord+1);
      strcat(lacAux,ksSPACE);
      *ptr_lacWord=”;
      ptr_lacWord=strrchr(lacString,kcSPACE);
      }
      strcat(lacAux,lacString);
      strcpy(lacString,lacAux);
      }

  • rka143

    The following are problems with mentioned program:
    1. Does not give correct result if string start with space (‘ ‘)
    Example:- Input: ” I have” output: “have I” Correct: “have I ”
    2. Making unneccessary call to reverse function in the case of multiple space in between (optimization).
    Example:- Input: “Ram Shyam” there is 2 space betwen Ram and Shyam.
    In this case extra call to reverese function has made when begin_word point to index 2 (space) and temp=2.

    I believe the correct solution should be:

     
    void reverseWords(char *s) 
    {   
    	char *word_begin = NULL;   
    	char *temp = s; 
    	/* temp is for word boundry */    
    	/*STEP 1 of the above algorithm */  
    	while( *temp )   
    	{     
    	/*This condition is to make sure that the string start with valid character (not space and  or '\0') only*/
    		if (( word_begin == NULL ) && (*temp != ' ') && (*temp != '\0'))    
    		{
    			word_begin=temp;
    		}     
    		if(word_begin && ((*(temp+1) == ' ') || (*(temp+1) == '\0')))
    		{       
    			reverse(word_begin, temp);       
    			word_begin = NULL;     
    		}
    		temp++;	
    	} /* End of while */     
    	/*STEP 2 of the above algorithm */  
    	reverse(s, temp-1); 
    } 
     

    Please let me know if there is something worng in solution.

    • GeeksforGeeks

      @rka143: Thanks for suggesting the changes to original version. We have added this function to the original post.

  • Ravi
     
    //using recursion
    void printWordReverse(char *string){
        char a[100];//max word length
        int i=0;
        while(*string != ' ' && *(string) != '\0'){
            a[i++] = *string;
            string++;
        }
        if(*string != '\0')
        printWordReverse(++string);
        a[i] = '\0';
        printf("%s ", a);
    } 
  • Crime_Master_GoGo

    I am not to clear about the
    time Complexity, i think should O(n*n) in my opinion…

    Consider this case when entire sentence is just one word

    “ThisIsAString”

    How many times did we visit the chracter “g”
    two times …

    When we visited character ‘g’ for the second time…
    Did we not have to go through entire string once again?

  • Dhanya
     
    // WordRev.cpp : Defines the entry point for the console application.
    //
    #include "stdafx.h"
    /*REVERSING A SENTENCE*/
    void reversefn(char *strng);
    void reverse(char*,int,int);
    
    int main()
    {
    
    	char strng[100];
    	gets(strng);
    
    	reversefn(strng);
    	printf("Reversed %s",strng);
    		return 0;
    }
    
    void reversefn(char *a)
    {
    	int beg = 0;
    	char *temp = a;
    	int end = 0;
    	while(*temp)
    	{
    		if(	*temp == ' ')
    		{
    			reverse(a,beg,end-1);
    			beg = end+1;
    		}
    		temp++;
    		end++;
    
    	}
    	reverse(a,beg,end-1);
    	reverse(a,0,end-1);
    }
     
    void reverse(char a[],int beg,int end)
    {
    	char temp ;
    	while(beg <end)
    	{
    		temp = *(a+beg);
    		*(a+beg) = *(a+end);
    		*(a+end) = temp;
    		beg++;
    		end--;
    
    	}
    }
     
    • Dhanya
       
      void reverse(char a[],int beg,int end)
      {
          char temp ;
          while(beg <=(beg + end)/2)
          {
              temp = *(a+beg);
              *(a+beg) = *(a+end);
              *(a+end) = temp;
              beg++;
              end--;
       
          }
      }
       
  • Gopal
     char *temp = s; /* temp is for word boundry */
     

    But s is pointing to beginning of string right?
    should temp not point to end o string for this to work..
    pls do tell me if i got the logic wrong

  • raj

    why u say, Time Complexity: O(n)
    its O(n) or O(2n)
    going through the string 2 times(once for step 1 and second time for step2).

    could you please give the brief idea, how to calculate the TIME and SPACE Complexity?

    you are not using extra memory that’s why Space Complexity: O(1)?
    if i use temp array to copy the reversed array than, Space Complexity: O(2) ?

    • Sandeep

      In time/space complexity analysis, we generally omit all the constants. By definition of Big O notation, 2n (or cn for any constant c) is equal to O(n). And 2 (or any other constant c) is equal to O(1). Hope this helps. Please read the wiki page (http://en.wikipedia.org/wiki/Big_O_notation) for more details.

  • gunjan

    public static void main(String[] args) {
    String s = "i like this program very much";
    String[] strArray =s.split(" ");
    StringBuffer sb = new StringBuffer();
    for(int i=strArray.length-1;i>=0;i–)
    {
    sb.append(strArray[i]);
    sb.append(" ");
    }
    System.out.println(sb.toString());
    }

    • http://mobilityworld.wordpress.com/ Punit

      I assume the interviewer will not let you use library functions for such a simple problem. I was asked such a problem in one of the interviews and the interview specifically told me not to use them.