Below are some simple programming problems and several approaches to each.  To see the code for an approach, click its "See Code" button.

Reverse the word order of a sentence.  All characters are considered parts of words except the space character, i.e., the space character delimits words.  Leading and trailing blanks are allowed.  For example:

"this is a sentence, reverse the word order"  will have the reverse order of:  "order word the reverse sentence, a is this"

Enter a string to be reversed:     
Approach One - Create A New String One pass over old string. Copy words (and spacing) to a new string.
Result string:   
Approach Two - "Bubble Sort" One pass over old string. "Bubble sort" within same string.  Store word to move in a temp string, then move remaining unprocessed portion of string to beginning and insert temp string at position in the same string.
Result string:   
Approach Three - Reverse string characters and then word characters Two passes over the string.  First pass reverse order of characters, store single character in temp while reversing within the same string.  Second pass (actually within the first pass) reverse each word's characters into proper order, again store single character in temp while reversing.

This method, within the same string, will not work in javascript because, similar to java, strings are immutable:

"There are two ways to access an individual character in a string.  ...  In both cases, attempting to set an individual character won't work.  Trying to set a character through charAt results in an error, while trying to set a character via indexing does not throw an error, but the string itself is unchanged."  Reference:  https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String#Summary

Result string:   
Future problem here.

Contact    Copyright © 2008, Shoestring Solutions, All rights reserved.  Last updated November 7, 2008