Reverse words in a given string


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


s = “tutorial cup makes programming easy”

“easy programming makes cup tutorial”

Time Complexity : O(n)


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;

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] != ' ') )
        //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";
  return 0;

Try It


Leave a Comment

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions