跳轉到

Reverse words

題目大意

完成一個功能,它接受一個字串變數作為參數,將字串中的每個字詞反轉,並保留字串中的所有空格。

範例

"This is an example!" ==> "sihT si na !elpmaxe"
"double  spaces"      ==> "elbuod  secaps"

自己的答案

<?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;
}
如果要使用內建陣列函數的話 * 先使用strrev函數翻轉整個字串 * 將反轉字串根據空格分割成陣列 * 接著使用array_reverse函數將陣列轉回去原本的方向 * 使用implode函數將陣列合併成字串
<?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;

}
簡化後的程式碼
<?php
function reverseWords($str) {
    return implode(' ', array_reverse(explode(' ', strrev($str)))) ;
}