字符串倒序排列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/youcijibi/article/details/88103622
<?php
$str = 'whoareyou';

//一,使用内置函数strrev().

//二,二分法,将字符串按照首尾呼应的格式调换顺序

//012345678  9-0-1
//012345678  9-1-1
//012345678  9-2-1
$len = strlen($str);
//不能使用count或sizeof
$mid = floor($len/2);  //二分法
for ($i=0; $i<$mid; $i++) {  //索引从0开始,而$len从1开始计长度,所以
    $temp = $str[$i];
    $str[$i] = $str[$len - $i - 1];
    $str[$len - $i - 1] = $temp;
}
 //三,循环截取
$result = '';
for ($i=1; $i<=strlen($str); $i++) {
    $result .= substr($str, -$i, 1);
}
echo $result;

//四,递归
/**
 * 递归实现对字符串的逆序排列(效率低)
 * @param string $str 源字符串
 * @return string 返回逆序后的字符串
 */
function reverse($str='') {
    static $result = '';
    /* 用堆栈来理解递归调用 */
    if (strlen($str) > 0) {
        reverse(substr($str, 1)); //递归中每次执行到这儿时程序将再次调用reverse
        $result .= substr($str, 0, 1); //当strlen($str) > 0条件不满足时执行到result时开始归数据
        //此句必须放在上一语句之后
    }
    return $result;
}

猜你喜欢

转载自blog.csdn.net/youcijibi/article/details/88103622