December 8, 2010
Reverse String Word by Word
Problem
Write a program to reverse an English sentence word by word not character by character. For example if the sentence is “I love Pizza so much” the program should print “much so Pizza love I”
Solution
One solution is to split the sentence into tokens using the space character as the separator then print the tokens in reverse order
Code
Here is how to do that in Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#!/usr/bin/perl # Input sentence $sentence = "I love Pizza so much"; # Split the sentence into tokens # The first parameter is the separator @tokens = split (" ", $sentence); # Print the tokens in reverse order # $#tokens is the Perl syntax to get the tokens array size for ($i = $#tokens; $i >= 0; $i--) { print $tokens[$i] . " "; } |