Reverse string without strrev

前端 未结 23 974
忘了有多久
忘了有多久 2020-12-13 13:19

Some time ago during a job interview I got the task to reverse a string in PHP without using strrev.

My first solution was something like this:

23条回答
  •  一整个雨季
    2020-12-13 14:09

    You can use the fact that in PHP a string can be thought of as an array of characters.

    Then basically what you want to do is to replace each character $i on the left side of the middle of the string with the character $j on the right side of the middle with the same distance.

    For example, in a string of seven characters the middle character is on position 3. The character on position 0 (distance 3) needs to be swapped with the character on position 6 (3 + 3), the character on position 1 (distance 2) needs to be swapped with the character on position 5 (3 + 2), etc.

    This algorithm can be implemented as follows:

    $s = 'abcdefg';
    
    $length = strlen($s); 
    for ($i = 0, $j = $length-1; $i < ($length / 2); $i++, $j--) {
        $t = $s[$i];
        $s[$i] = $s[$j];
        $s[$j] = $t;
    }
    
    var_dump($s);
    

提交回复
热议问题