Wednesday, March 13, 2013

Reverse order of words

Here is a simple programming problem. Take the string "Done is better than perfect" and reverse the order of the words. Final output should be "Perfect than better is done"

Here is a very simple solution written in PHP.


//original string
$s= 'Done is better than perfect';
//put all the words to lowercase
$s= mb_strtolower($s); 

//split the string by spaces and put in in an array
$arr = explode(" ", $s);
//reverse sort the array
$arr = array_reverse($arr);

//Put the first char of first word to uppercase

//print the output
echo implode(' ', $arr);

No comments: