[英]How to check if two strings contain the same letters?
$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
我要找的話怎么辦?
考慮到以下兩個變量,我想一個解決方案可能是:
$textone = "pate";
$texttwo = "tape";
1.首先,拆分字符串,得到兩個字母數組:
$arr1 = preg_split('//', $textone, -1, PREG_SPLIT_NO_EMPTY);
$arr2 = preg_split('//', $texttwo, -1, PREG_SPLIT_NO_EMPTY);
請注意,正如@Mike在他的評論中所指出的,不是像我第一次那樣使用preg_split()
,對於這種情況,最好使用str_split()
:
$arr1 = str_split($textone);
$arr2 = str_split($texttwo);
2.然后,對這些數組進行排序,因此字母按字母順序排列:
sort($arr1);
sort($arr2);
3.在此之后,破滅的陣列,要創造一個所有的字母按字母順序排列的話 :
$text1Sorted = implode('', $arr1);
$text2Sorted = implode('', $arr2);
4.最后,比較這兩個詞 :
if ($text1Sorted == $text2Sorted) {
echo "$text1Sorted == $text2Sorted";
}
else {
echo "$text1Sorted != $text2Sorted";
}
將這個想法變成比較函數會給你以下代碼部分:
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 />";
}
}
並在你的兩個單詞上調用該函數:
compare("pate", "tape");
compare("pate", "tapp");
會得到以下結果:
aept == aept
aept != appt
使用===
和!==
if ($textone === $texttwo) {
echo "The two strings contain the same letters";
}else{
echo "The two strings NOT contain the same letters";
}
要么
if ($textone === $texttwo) {
echo "The two strings contain the same letters";
}
if ($textone !== $texttwo) {
echo "The two strings NOT contain the same letters";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.