题目:字符串反转,但是单词不反转,不能用内库函数但是可以用(strlen)
demo:I am coder
结果:coder am I
本来一个用库函数:
<?php
$str="I am coder !";
echo implode(' ',array_reverse(str_word_count($str,1)));
?>
只能用最简单的算法
1.那整体反转
2.找到每一个单词反转过来
<?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) )
I
coder am I
coder! am I
! coder am I