计算您可以从较大文本的字母组成给定单词的次数

问题描述 投票:0回答:4

我想创建一个函数,你可以看到你可以从文本中生成给定单词多少次。

例如:

文字是:火腿现在欣喜若狂地使用口语练习可能会重复。他本人显然非常关心我的普遍关注。它的宽容胜过享受。跟注观察谁按下加注键。可连仪的惊讶丝毫不影响他一动不动的喜好。宣布说男孩预防措施不受影响,困难会改变他。

$text = "Ham followed now ecstatic use speaking exercise may repeated.
Himself he evident oh greatly my on inhabit general concern. It allowance 
prevailed enjoyment in it. Calling observe for who pressed raising his. Can 
connection instrument astonished unaffected his motionless preference. 
Announcing say boy precaution unaffected difficulty alteration him.";

$word = "Potato";

我想知道“土豆”这个词你能写多少次。预计计数为

6
次。

我从这样的事情开始:

function count($text) {
    for ($i = 0; $i <= strlen($text); $i++) {
        if ($text[$i] == "p") {
            $p = 0;
            $p++;
            echo $p;
        }
    }
}
php string count character find-occurrences
4个回答
0
投票

首先,你不能声明

count
函数,因为它已经被声明了。

试试这个:

function countt($text, $word, $count = 0) {
    $found = '';
    for($i=0; $i<strlen($word);$i++){
        for($j=0; $j<strlen($text);$j++){
            if($word{$i} === $text{$j}){
                $text = substr($text,0,$j).substr($text,$j+1);
                $found.= $word{$i};
                if($found === $word){
                    $count++;
                    return countt($text,$word,$count);
                }
                break;
            }
        }
    }
    return $count;
}

echo countt($text,'potato');//6

说明:函数查找文本中单词的每个字母的出现并将其从文本中删除。一旦它完成与搜索的单词相同的新单词,它就会使用新文本再次调用此函数,该函数会错过那些使用过的字母,直到没有更多的字母可以完成另一个单词。

你可以在这里玩它:

http://sandbox.onlinephpfunctions.com/code/ba579be33a82a6abdc0fc285cc4a631186eb7b29


0
投票

此函数可帮助您获取

paroto
在该字符串中使用了多少次

echo substr_count($text, $word);

0
投票

我的方法是遍历字典中存储每个字符的文本,其中键是字母,值是文本中出现的次数。处理完文本后,您可以计算出您可以拼写马铃薯的次数


0
投票

将两个输入字符串(假设仅包含单字节字符)转换为小写后,对两个字符串调用

count_chars()
以填充字符映射及其出现次数。

然后循环遍历针的字母并计算每个输入“单词”找到该字母的次数以及使用该字母的次数。

在迭代时保持最低的计算值,并在该值变为零时立即中断循环。

代码:(演示

$needleCharCounts = count_chars(strtolower($word), 1);
$haystackCharCounts = count_chars(strtolower($text), 1);

$result = null;
foreach ($needleCharCounts as $letter => $count) {
    $result = min($result ?? PHP_INT_MAX, intdiv($haystackCharCounts[$letter] ?? 0, $count));
    if ($result === 0) {
        break;
    }
}
echo $result ?? 0;
// 6
© www.soinside.com 2019 - 2024. All rights reserved.