Posted on Thursday, September 10, 2009 at 3:23 PM
In the
first part I showed how to reverse the words in a string with a simple Perl script. Perl is an excellent language for string manipulation; however, the original question was how could I write the algorithm using C# or C++. Take the following simple string:
A stitch in time saves nine
One way to reverse the words would be to take parse the string into individual words. These words could be stored in individual strings or they could be pushed onto a stack. For example (using _ to indicate the pointer position in the string for each operation and using {} to indicate stack elements with as {top...bottom}):
Before parsing: _A stitch in time saves nine stack = {}
1st Read: A_stitch in time saves nine stack={A}
2nd Read: A stitch_in time saves nine stack={stitch A}...