dsai1991 2011-07-24 15:54
浏览 755
已采纳

如何检查两个字符串是否包含相同的字母?

$textone = "pate"; //$_GET
$texttwo = "tape";
$texttre = "tapp";

if ($textone ??? $texttwo) {
echo "The two strings contain the same letters";
}
if ($textone ??? $texttre) {
echo "The two strings NOT contain the same letters";
}

What if statement am I looking for?

  • 写回答

2条回答 默认 最新

  • dongzhu7329 2011-07-24 15:59
    关注

    I suppose a solution could be to, considering the two following variables :

    $textone = "pate";
    $texttwo = "tape";
    


    1. First, split the strings, to get two arrays of letters :

    $arr1 = preg_split('//', $textone, -1, PREG_SPLIT_NO_EMPTY);
    $arr2 = preg_split('//', $texttwo, -1, PREG_SPLIT_NO_EMPTY);
    

    Note that, as pointed out by @Mike in his comment, instead of using preg_split() like I first did, for such a situation, one would be better off using str_split() :

    $arr1 = str_split($textone);
    $arr2 = str_split($texttwo);
    


    2. Then, sort those array, so the letters are in alphabetical order :

    sort($arr1);
    sort($arr2);
    


    3. After that, implode the arrays, to create words where all letters are in alphabetical order :

    $text1Sorted = implode('', $arr1);
    $text2Sorted = implode('', $arr2);
    


    4. And, finally, compare those two words :

    if ($text1Sorted == $text2Sorted) {
        echo "$text1Sorted == $text2Sorted";
    }
    else {
        echo "$text1Sorted != $text2Sorted";
    }
    



    Turning this idea into a comparison function would give you the following portion of code :

    function compare($textone, $texttwo) {
        $arr1 = str_split($textone);
        $arr2 = str_split($texttwo);
    
        sort($arr1);
        sort($arr2);
    
        $text1Sorted = implode('', $arr1);
        $text2Sorted = implode('', $arr2);
    
        if ($text1Sorted == $text2Sorted) {
            echo "$text1Sorted == $text2Sorted<br />";
        }
        else {
            echo "$text1Sorted != $text2Sorted<br />";
        }
    }
    


    And calling that function on your two words :

    compare("pate", "tape");
    compare("pate", "tapp");
    

    Would get you the following result :

    aept == aept
    aept != appt
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出