題目:字符串反轉,可是單詞不反轉,不能用內庫函數可是能夠用(strlen)php
demo:I am coder 結果:coder am I算法
原本一個用庫函數:函數
<!-- lang: php --> <?php $str="I am coder !"; echo implode(' ',array_reverse(str_word_count($str,1))); ?>
只能用最簡單的算法 1.那總體反轉 2.找到每個單詞反轉過來ui
<!-- lang: php --> <?php /** *@param $str(string type) *@function reverse $str but the word is not. *@return reverse string *@time 2014-05-13 *@version 1.0 **/ function str_reverse($str=""){ $j=strlen($str); $i=0; //if string len <2 return self if($j<2){ return $str; } //first reverse string all while($i<$j){ $tmpchar=$str[$i]; $str[$i]=$str[$j]; $str[$j]=$tmpchar; $j--; $i++; } //printf(" string=%s\n",$str); //second only reverse word $i=0; while($str[$i]){ if($str[$i]!=' '){ $begin=$i; while($str[$i]&&$str[$i]!=" "){ $i++; } $i--; $end=$i; while($end>$begin){ $tmpchar=$str[$end]; $str[$end]=$str[$begin]; $str[$begin]=$tmpchar; $end--; $begin++; } } $i++; } //printf(" string=%s\n",$str); return $str; } //one test $str="I"; echo str_reverse($str),"\n"; //two test $str="I am coder"; echo str_reverse($str),"\n"; //third test $str="I am coder!"; echo str_reverse($str),"\n"; //four test $str="I am coder !"; echo str_reverse($str),"\n"; ?>
運行結果(PHP 5.2.10 (cli) (built: Dec 31 2011 17:20:47) )code
I字符串
coder am Istring
coder! am Iio
! coder am Ifunction