Reverse all the words in a sentence.

Given string containing a set of words separated by white spacer we would like to transform it to a string in which the words appear in the
reverse order. For example, “Alice likes Bob” will become “Bob likes Alice”. We do not need to keep the original string.

This is very simple problem, If you try to figure out the position for each character in a single pass, it becomes fairly complex. If you do this in two stages, it becomes fairly easy. In the first step, reverse the entire string and in the second step reverse each word.

#include <algorithm>
#include <string.h>
#include <iostream>

void reverse_string( char *input, size_t length ) {
	for ( int i = 0; i < length / 2; i++) {
		std::swap(input[i], input[ length - i - 1] );
	}
}
void reverse_word(char *input) {
	size_t length = strlen(input);
	reverse_string(input, length);
	int start = 0;
	while ( start < length ) {
		int end = start;
		// find the first space location
		while ( end < length && input[end] != ' ') {
			end++;
		}
		reverse_string( input + start, end - start );
		start  = end + 1;
	}

}
int main( int argc, char **argv) {
	char test[] = "ram is costly";
	reverse_word(test);
	std::cout << test << std::endl;

	return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s