Reverse words in a given string

Given a string, write a function that will print the words of a string in reverse order

Example

INPUT
s = "tutorial cup makes programming easy"

OUTPUT
"easy programming makes cup tutorial"

Time Complexity : O(n)

Algorithm

Traverse the string

1. Reverse the individual words   

2. After reversing the words, reverse the whole sentence from start to end

C++ Program

#include <bits/stdc++.h>
using namespace std;

//prototype
void reverse(char *start, char *end);
 
/*Function to reverse words*/
void reverseWords(char *s)
{
    char *word_begin = NULL;
    char *temp = s; /* temp is for word boundry */
 
 	//Reversing each word
    //Traversing the string
    for(int i=0;i<strlen(s);i++ )
    {
        //string should have a proper start ie,word_begin, which is not space ie,temp[i] != ' '
        if (( word_begin == NULL ) && (temp[i] != ' ') )
        {
            word_begin=(temp+i);
        }
        //Each word, reverse the word
        //In below if condition words are considerd by seeing space 
        if(word_begin && (temp[i+1] == ' ') || (temp[i+1] == '\0'))
        {
            reverse(word_begin, (temp+i));
            word_begin = NULL;
        }
        
    }
 
    //Reversing the entire string
    reverse(s, (temp+strlen(s)-1));
}

//this function will reverse the string, when given starting and ending pointers to the string
void reverse(char *start, char *end)
{
  char temp;
  while (start < end)
  {
    temp = *start;
    *start++ = *end;
    *end-- = temp;
  }
}
 
/* Driver function to test above functions */
int main()
{
  char s[] = " tutorial cup makes programming easy";
  reverseWords(s);
  cout<<s;
  return 0;
}
Try It

 


Next > < Prev
Scroll to Top