Reverse words
題目大意
完成一個功能,它接受一個字串變數作為參數,將字串中的每個字詞反轉,並保留字串中的所有空格。
範例
自己的答案
<?php
function reverseWords($str) {
// Go for it
$count = strlen($str);
$output = "";
$temp = "";
for ($i = 0; $i<$count ;$i++) {
$char = $str[$i];
if (trim($char) == "") {
$output .= ($temp . $char);
$temp = "";
} else {
$temp = ($char.$temp);
}
}
return $output.$temp;
}
<?php
function reverseWords($str) {
//$str = 'ehT kciuq nworb xof spmuj revo eht yzal .god'
$output = strrev($str); //dog. lazy the over jumps fox brown quick The
$output = explode(" ",$output); //Array ( [0] => dog. [1] => lazy [2] => the [3] => over [4] => jumps [5] => fox [6] => brown [7] => quick [8] => The )
$output = array_reverse($output); //Array ( [0] => The [1] => quick [2] => brown [3] => fox [4] => jumps [5] => over [6] => the [7] => lazy [8] => dog. )
$output = implode(" ",$output);//The quick brown fox jumps over the lazy dog.
return $output;
}