Skip to content

Instantly share code, notes, and snippets.

@dautermann
Created November 13, 2014 03:51
Show Gist options
  • Save dautermann/806830b0b43af2c9c37d to your computer and use it in GitHub Desktop.
Save dautermann/806830b0b43af2c9c37d to your computer and use it in GitHub Desktop.
Q) How does one reverse the characters in a string (e.g. “god” becomes “dog”). This classic computer science question can then be 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”)? A) Here’s the full answer (and …
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 <strlen(wholeString); rightIndex++)
{
if((rightIndex == ' ') || (rightIndex == 0))
{
reverseString(wholeString, leftIndex, rightIndex-1);
leftIndex = rightIndex+1; // go beyond the space
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment