【问题标题】:Check if a word can be created from a random letter string using PHP检查是否可以使用 PHP 从随机字母字符串创建单词
【发布时间】:2017-10-25 22:04:11
【问题描述】:
<?php
    $randomstring = 'raabccdegep';
    $arraylist = array("car", "egg", "total");
?>

$randomstring 上方是一个包含一些字母的字符串。 我有一个名为 $arraylist 的数组,其中包含 3 个单词,例如 'car' , 'egg' , 'total'

现在我需要使用数组中的单词检查字符串并打印是否可以使用字符串创建单词。 例如,我需要一个类似的输出。

car is possible.
egg is not possible.
total is not possible.

还请检查字母的重复。即,beep 也是可能的。因为字符串包含两个e。但是egg是不可能的,因为g只有一个。

【问题讨论】:

  • 字符在验证字符串上使用后会掉下来吗?例如我们搜索汽车,验证字符串是“thecar”(找到汽车然后验证字符串现在是)->“the”?
  • 没有。可以重复使用。

标签: php arrays string word letter


【解决方案1】:

这应该可以解决问题:

<?php
        $randomstring = 'raabccdegep';
        $arraylist = array("car", "egg", "total");

        foreach($arraylist as $word){
            $checkstring = $randomstring;
            $beMade = true;
            for( $i = 0; $i < strlen($word); $i++ ) {
                $char = substr( $word, $i, 1 );
                $pos = strpos($checkstring, $char);
                if($pos === false){
                    $beMade = false;
                } else {
                    substr_replace($checkstring, '', $i, 1);    
                }
            }
            if ($beMade){
                echo $word . " is possible \n";
            } else {
                echo $word . " is not possible \n";
            }
        }
    ?>

【讨论】:

  • 当我尝试这个时。我有'鸡蛋是可能的'。但根据我的需要,“鸡蛋”这个词不应该是可能的。
【解决方案2】:
function find_in( $haystack, $item ) {
    $match = '';
    foreach( str_split( $item ) as $char ) {
        if ( strpos( $haystack, $char ) !== false ) {
            $haystack = substr_replace( $haystack, '', strpos( $haystack, $char ), 1 );
            $match .= $char;
        }
    }
    return $match === $item;
}

$randomstring = 'raabccdegep';
$arraylist = array( "beep", "car", "egg", "total");

foreach ( $arraylist as $item ) {
    echo find_in( $randomstring, $item ) ? " $item found in $randomstring." : " $item not found in $randomstring.";
}

【讨论】:

  • 完美。谢谢。最后 3 行应该在 $arraylist 的 foreach 循环中。
猜你喜欢
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 2014-01-25
相关资源
最近更新 更多