How does one reverse the characters in a string (e.g. “god” becomes “dog”). This classic computer science question was then extended to the more interesting question: how does one reverse all the characters in a sentence, but keeping the actual words in place (e.g. “cat chases dog” becomes “dog chases cat”)?
Sigiloso
Here’s the full answer I came up with. One would pass the entire “cat chases dog” string into the “reverseTheEntireString” function and after the string is transmogrified into “god sesahc tac”, the next set of lines reverses the characters of each word into “dog chases cat”. reverseString(char *array, int start, int end) { int rightIndex = end; for(int leftIndex = start; leftIndex < rightIndex; leftIndex++) { char swapChar = array(rightIndex); array(rightIndex) = array(leftIndex); array(leftIndex) = swapChar; rightIndex--; } } reverseTheEntireString(char *wholeString) { // reverse the entire string.... reverseString(wholeString, 0, strlen(wholeString)); // then step through the entire string looking for either the null // terminator or a space... then reverse everything within the // leftIndex & rightIndex range int leftIndex = 0; for(int rightIndex = 0; rightIndex