如何检查两个字符串是否包含相同的字母? [英] How to check if two strings contain the same letters?

查看:539
本文介绍了如何检查两个字符串是否包含相同的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$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";
}

我要查找什么if语句?

推荐答案

我认为,考虑以下两个变量,可以解决这个问题:

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

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


1..首先,拆分字符串,以获得两个字母数组:


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);

请注意,正如@Mike在其评论中指出的那样,不要像这样使用 preg_split() 我首先做了这种情况,最好使用 str_split() :

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.然后,对这些数组进行排序,以使字母按字母顺序排列:


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

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


3.之后,对数组进行内插,以创建单词,其中所有字母均按字母顺序排列:


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

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


4.,最后,比较这两个单词:


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");

将为您带来以下结果:

aept == aept
aept != appt

这篇关于如何检查两个字符串是否包含相同的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆