Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

reverse
words
string

Reverse the order of words in a string

Educative Answers Team

Given a string of words, we need to implement a function which reverses the order of the words in the string. For example, the string “I work at Educative” should become “Educative at work I​”.

svg viewer

Algorithm

There are various methods used to reverse a given string; one of the most widely used algorithms is described below:

  • First, reverse the letters in the individual words in the string. For example, the string “I work at Educative” should become “I krow ta evitacudE”.

  • Then, reverse the whole string. So, “I krow ta evitacudE” becomes “Educative at work I”.

The parameter(s) of the reverse function will depend on the algorithm in the respective language. In C++, the function takes a start and an end pointer to the string as parameters and reverses it by swapping the first and the last letters; ​it then swaps the second and the second to the ​last letter, and so on.

Code

The algorithm above is implemented in the code snippet below:​

#include <iostream>
using namespace std;

// reverse function which takes the pointer to starting
// and ending character
void reverse(char* start, char* end)
{
  // loop over the word until the start meets end
  // in the middle
  for (start ; start < end ; start++)
  {
    // swap
    char temp;
    temp = *start;
    *start = *end;
    *end = temp;

    // move to the previous letter
    end--;
  }

}

int main() {
  
  string str = "I work at Educative";
  
  // pointers to starting characters of the string
  char* ind = &str[0];
  char* new_word = &str[0];

  // while there exists a character
  while(*ind)
  {
    // if a space is found, call reverse on the word
    // before the space
    if (*ind == ' ')
    {
      reverse(new_word, ind-1);
      
      // set the marking of a new word i.e right after
      // the space
      new_word = ind+1;
    }
    ind++;
  }

  // reverse the letters in the last word
  // the last word is not catered in the loop above
  reverse(new_word,--ind);

  // reverse the whole string
  reverse(&str[0], ind);
  

  cout << str;
  return 0;
}

RELATED TAGS

reverse
words
string
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring