Reverse a Sentence

Yet another “classic” programming interview question.

The Question

Given a sentence as input, reverse the words but not their individual letters.

Thus, the sentence “One two three” would result in “three two One”

The Answer

Using an array is the only sensible way to accomplish this. If you don’t, you’ll have a headache of a time scanning through for whitespace, storing the characters until the next whitespace and repeating until the end of the sentence where you display it onscreen.

In my solution, I read in a string passed to the script into an array (the -a sentence_array part) as arguments separated by whitespace (i.e. a standard sentence). Note that I don’t need to specify IFS=’ ‘ since by default, IFS separates by whitespace (spaces, tabs and newlines).

Using a for loop, I simply iterate from the end to the beginning, one element at a time in the array. Since all whitespace is used as deliminators, the array will be full (i.e. not sparse), and display with only one space between the words when echoed back.

#set -xv

read -r -a sentence_array <<< "$1"

for (( i="${#sentence_array[@]}"; i>=0; i-- ))

     sentence_string="$sentence_string ${sentence_array[i]}"

echo "Reversed sentence is:$sentence_string"

The output of the script will be as follows.

$ ./reverse_sentence "This is a nice, long, sentence with a number of words and spaces that I wouldn't want to reverse manually."
Reversed sentence is: manually. reverse to want wouldn't I that spaces and words of number a with sentence long, nice, a is This

Pretty easy, huh?

Tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

Protected by WP Anti Spam