Sunday, October 13, 2013

Reversing the words in the string

Given a string, how do we reverse the words inside the string?

For example if the input string is "this is a test" the output should be "test a is this".

The algorithm is simple. This can be done in two steps. The first step is to reverse the entire string. In the second step we traverse the string to find the individual words separated by spaces and reverse them.

In the following program I have used C++ STL string instead of a C-style null terminated string. To read a string including spaces I have used getline(cin,str) function. I have also used reverse(str.begin(), str.end()) as a helper function from standard template library for simplicity. 

Here is the C++ program.