[STRING] Reverse Words
16 September, 2013 - 1 min read
Problem: Reverse the words in a sentence. For example "Reversed Words" should become "Words Reversed". Comment: This is one of most frequently asked interview questions on string manipulation.
Solution: First we reverse the entire string and then reverse each word of this reversed string.
Code:
void reverse(char str[], int beginIndex, int endIndex)
{
while(beginIndex < endIndex) // keep swaping characters as long as
// begin index is less than end index
{
// swap the characters
char temp = str[beginIndex];
str[beginIndex] = str[endIndex];
str[endIndex] = temp;
beginIndex++; //increment the begin index
endIndex--; //decrememnt the end index
}
}
void reverse_words(char str[])
{
reverse(str, 0, strlen(str)-1);
int currentIndex = 0;
int wordBeginIndex = 0;
int wordEndIndex = -1;
while(str[currentIndex])
{
if(str[currentIndex + 1] == ' ' // if we are at the word
|| str[currentIndex + 1] == '') // boundary or end of the string
{
wordEndIndex = currentIndex;
reverse(str, wordBeginIndex, wordEndIndex);
wordBeginIndex = currentIndex + 2;
}
currentIndex++;
}
}
END