Fog Creek Software
Discussion Board

Reverse words in a String (an easier solution)

Well as I just found my way to this site, I would like to post my much simpler solution to "reverse words in a string".

Why don't you simply split the string at the spaces (i.e. using the split() function in perl) generating an array of the words in order, then just loop over the array in inverse order, and use join() (or the appropriate string command to join 2 strings) to join each member of the array to the return string along with the appropriate spaces inbetween the words.

This solution is 1 loop over the number of letters in the string (split()) and 1 loop over number of words in the string.

This is usually much faster then 2 loops over number of letters in the string.

Brian Summers
Wednesday, July 24, 2002

Hahahaha.... I think the intent was to write a C function to reverse the strings not a PERL function, but now that you point it out, no particular language was specified in the problem statement.

So, I choose to use the WF#++ language (I just invented it) and I will call the ReverseWordsInString() function.  Presto.  Done in one step.  That's a standard library call in the WF#++ language.

It reminds me of my first course in digital circuit design.  I had to do a project to build a digital voltmeter.  Of course the first thing I did was pick up the IC reference book and say, "OK, where's the digital voltmeter chip?"

The prof. laughed and said I'd make a good designer.

William Frantz
Friday, July 26, 2002

This will reverse the words in the string, but it won't do it *in place*, as specified in the problem. If you can write an implementation of "join" which works in place (i.e. without allocating any extra memory) then this would be a solution.

Joe Bayes
Monday, July 29, 2002

*  Recent Topics

*  Fog Creek Home