Reverse words of a string

This was just a small exercise posted on algogeeks. I tried to implement it. The reason I am interested in this code is because, I was asked this question at NetApp interview :P And I gave a pathetic iterative solution, which I didn’t like at that time. And I thought of using recursion while returning. So here is the code in “C” and then my favorite “Python”
C Version:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char str[] = "This is a new world";
char sstr[sizeof(str)];

char *print_rev(char *tok)
{
	char *nstr = NULL;
	if (tok) {
		nstr = strtok(NULL, " ");
		print_rev(nstr);
		if (nstr) {
//			printf("%s ", nstr);
			strcpy(&sstr[strlen(sstr)], nstr);
			sstr[strlen(sstr)] = ' ';
		}
	}
	return nstr;

}

int main(int argc, char *argv[])
{
	char *nstr;
	printf("Org string --> %s\n", str);
	nstr = strtok(str, " ");
	print_rev(str);
	strcpy(&sstr[strlen(sstr)], nstr);
	printf("New string --> %s\n", sstr);
	return 0;
}

Python version:


#!/usr/bin/python
import sys
print " ".join((sys.argv[1].split())[::-1])

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