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”.
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.
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 charactervoid reverse(char* start, char* end){// loop over the word until the start meets end// in the middlefor (start ; start < end ; start++){// swapchar temp;temp = *start;*start = *end;*end = temp;// move to the previous letterend--;}}int main() {string str = "I work at Educative";// pointers to starting characters of the stringchar* ind = &str[0];char* new_word = &str[0];// while there exists a characterwhile(*ind){// if a space is found, call reverse on the word// before the spaceif (*ind == ' '){reverse(new_word, ind-1);// set the marking of a new word i.e right after// the spacenew_word = ind+1;}ind++;}// reverse the letters in the last word// the last word is not catered in the loop abovereverse(new_word,--ind);// reverse the whole stringreverse(&str[0], ind);cout << str;return 0;}
Free Resources