使用类而不是使用预定义函数来反转字符串:

时间:2017-11-26 02:43:09

标签: php algorithm

我已创建代码以检查其回文结构。现在,如果字符串不是回文,我希望它被反转。可以使用一个条件循环完成吗? 我的PHP代码:     

class user{

public function __construct() {
    if ($this->String_Rev()) {
        echo 'Yes, palindrome';

    } else {
        echo 'not palindrome';
    }
}

public function String_Rev() {

   $str = "abba";

    $i = 0;

    while ($str[$i] == $str[strlen($str) - ($i + 1)]) {//Incrementing and decrementing the values in the string at the same time/
        $i++;


        if ($i > strlen($str)/ 2) {//If the  i goes ahead of half of its string then return true and stop its execution.
            return 1;
        }
    }
    return 0;
}

 }



 $obj = new user();

1 个答案:

答案 0 :(得分:0)

PHP中的字符串不是数组,但您可以像数组键一样选择字符串的字符索引,这使得以下内容成为可能:

<?php
$string = 'foobar';

$string_array = array();

//make an actual array of the characters first
//if you want this to be an object, do this part in your constructor,
//and assign this variable to an object property to work with.
for ($i=0; $i < strlen($string); $i++)
{
    $string_array[$i] = $string[$i];
}

echo implode( $string_array ); //prints 'foobar'

echo '<br>' . PHP_EOL;

echo implode( array_reverse( $string_array ) ); //prints 'raboof'

通过这样做,您可以轻松简化您的回文逻辑:

//in your case, this would probably be it's own method,
//using the aforementioned class property made in the constructor

$is_palindrome = implode( $string_array ) === implode( array_reverse( $string_array ) );