PHP 程序检查字符串是否为回文


2022年5月11日, Learn eTutorial
2738

什么是回文字符串?

字符串是字符的组合。如果一个字符串的反转与原始字符串相同,则它被认为是回文。例如,如果输入的字符串是 radar,那么如果检查它的反转,它也是 radar,所以它是一个回文字符串。在另一个例子中,如果字符串是 algorithm,那么如果检查它的反转,它将是 mhtirogla,这与原始字符串不相同,所以它不是回文字符串。

What is a palindrome

如何使用 PHP 检查字符串是否为回文

在此程序中,为了检查字符串是否为回文,我们使用了一个用户定义函数。在检查回文字符串时,程序将小写字母和大写字母视为不同,为了避免这种情况,我们在查找反转并将其与原始字符串进行比较之前,使用内置函数 strtolower() 将字符串转换为小写。这里我们首先接受用户的输入并将其存储到变量 char 中,然后调用带有参数 char用户定义函数 checkPalindrome()。在函数 checkPalindrome() 中,我们首先定义一个空字符串变量 str,用于存储字符串的反转。然后我们将变量 char 的值转换为小写并将其存储到变量 s 中,然后找到 char 的长度并将其存储到变量 len 中。然后我们执行 for 循环 来反转字符串。在 for 循环中,我们首先将 'len-1' 赋值给变量 i,并执行循环直到条件 'i >= 0' 变为假,并且在每次迭代中将变量 i 的值减 1。在循环体中,我们执行连接操作 'str . s[i]' 并将其赋值给变量 str。循环完成后,我们检查变量 s 的值是否与 str 相同,如果为真,则打印该字符串为回文,否则打印该字符串不是回文。

算法

步骤 1: 接受用户的字符串输入并将其存储在变量 char

步骤 2: 调用函数 checkPalindrome(),并将变量 char 的值作为参数

算法函数:checkPalindrome(char)

步骤 1: 赋值一个空字符串变量 str

步骤 2: 使用内置函数 strtolower() 将通过函数参数传递的值转换为小写,并将其赋值给变量 s

步骤 3: 查找变量 char 的长度并将其赋值给变量 len

步骤 4:'len - 1' 的计算值赋值给变量 i,并执行以下子步骤,直到条件 'i >= 0' 变为假,并在每次迭代中将变量 i 的值减 1

        (i) 将操作 'str . s[i]' 的值赋值给变量 str

步骤 5: 检查条件 's == str',如果条件为真,则打印输入的字符串为回文,否则打印该字符串不是回文

PHP 源代码

                                          <?php

function checkPalindrome($char)
{
    $str = "";
    $s = strtolower($char);
    $len = strlen($char);
    for ($i = ($len - 1); $i >= 0; $i--) {
        $str = $str . $s[$i];            // concatenating the character of each index with the value of variable str
    }
    if ($s == $str) {
        echo "$char is a palindrome string";
    } else {
        echo "$char is not a palindrome string";
    }
}

$char = readline("Enter the string: ");
checkPalindrome($char);
?>
                                      

输出

Example 1:
Enter the string: tenet
tenet is a palindrome string

Example 2:
Enter the string: website
website is not a palindrome string