检查两个字符串是否为字谜的 PHP 程序


2022 年 4 月 14 日, Learn eTutorial
2164

什么是字谜字符串?

字谜字符串是由相同字符集组成的两个字符串,其中字符的顺序是字符串中唯一的区别。.

例如,单词“silent”和“listen”是字谜。其他字谜示例有“peek”和“keep”。在这里我们可以看到相同的字母以不同的顺序用于形成有意义的单词。

anagram strings?

如何使用 PHP 检查两个字符串是否为字谜?

在此 PHP 程序中,我们接受用户输入的字符串并检查它们是否为字谜。

为了便于比较,我们使用 PHP 中的 strtolower() 函数将两个字符串都转换为小写。然后使用 str_split() 函数将其转换为数组。接下来,我们将使用 sort() 对这些数组进行排序,并使用 implode() 函数将数组再次转换为字符串。现在我们得到字符顺序相同的字符串,因此使用 strcmp() 函数比较它们,如果两者相同,则它们是字谜,否则它们不是字谜字符串。

算法

步骤 1: 将字符串接受到变量 str1str2

步骤 2: 将变量 str1str2 中的值赋给变量 s1s2

步骤 3: 使用条件 strlen(s1) != strlen(s2) 检查两个字符串的长度是否相同,如果为 true,则打印输入的字符串不是字谜并退出程序,否则执行以下步骤

步骤 4: 使用内置函数 strtolower() 将变量 s1s2 中的字符串转换为小写,并将其赋给变量 s1s2

步骤 5: 使用内置函数 str_split() 将变量 s1s2 中的字符串转换为数组,并将其赋给变量 let1let2

步骤 6: 使用内置函数 sort() 对数组 let1let2 进行排序

步骤 7: 使用内置函数 implode() 将数组 let1let2 转换为字符串

步骤 8: 检查条件 strcmp(s1, s2) == 0,如果为 true,则打印它们是字谜,否则打印它们不是字谜


要解决 PHP 中的字谜字符串程序,我们需要了解以下主题,请参阅这些主题以获得更好的理解

PHP 源代码

                                          $str1 = readline("Enter the 1st string: ");
$str2 = readline("Enter the 2nd string: ");
$s1 = $str1;
$s2 = $str2;
if (strlen($s1) != strlen($s2)) {
    echo "The entered strings $str1 and $str2 are not anagram";
} else {
    $s1 = strtolower($s1);
    $s2 = strtolower($s2);
    $let1 = str_split($s1);
    $let2 = str_split($s2);
    sort($let1);
    sort($let2);
    $s1 = implode("", $let1);
    $s2 = implode("", $let2);
    if (strcmp($s1, $s2) == 0) {
        echo "The entered strings $str1 and $str2 are anagram";
    } else {
        echo "The entered strings $str1 and $str2 are not anagram";
    }
}
                                      

输出

Example 1
Enter the 1st string: race
Enter the 2nd string: care
The entered strings race and care are anagram

Example 2
Enter the 1st string: earth
Enter the 2nd string: heart
The entered strings earth and heart are anagram