如何确保没有字母,他的出现次数在登录系统的字符串中不超过 4 个?



我想知道是否有一个字母,它在一个大于4的字符串(名称(中。我有一个问题,我的示例代码不正确,因为当你这样写名字时:aaaAA它会说没有错误。因为数组中的字母是这样的("A","A",…(

我还有一个索引文件,Car Class。我只是想测试一下,这个函数是否有效。这个函数应该找出,一个字母是否重复了4个以上的例子:aaaaa;函数在这里应该说这是不允许的。aaaAA;函数在这里应该说这是不允许的。大写字母和小写字母必须平等对待

我能帮忙吗?

非常感谢大家。


public function checkLetterOccurence($newMarke)
{
//array of the letter
$letterKette = array('A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z');

for ($i = 0; $i < count(  $letterKette); $i++) {
if (substr_count($newMarke, $letterKette[i]) > 4) {
echo "there is a letter that is more than 4 written, and that is not allowed.";
die();
}
}
}


您必须将输入全部小写,然后计算字母的出现次数:

<?php
$input = 'aaaAA';
function checkLetterOccurence($input) {
$input = strtolower($input);
// Split text to array of letters, e.g. "hello" becomes ["h", "e", "l", "l", "o"]
$input = str_split($input);

// Here we will keep map of letters and how much time it appears in word
$count = [];

foreach ($input as $letter) {
// If there is no such letter added yet, we add new one with initial value 0. Next line will add +1 to it
$count[$letter] ??= 0; // Or if (!isset($count[$letter])) $count[$letter] = 0;
$count[$letter]++;
}

// Filter only those letters that appear more than 4 times in word 
$filteredInput = array_filter($count, fn($c) => $c > 4);

// If we have +4 same letter in word - write out error message
if (!empty($filteredInput)) {
echo "There is a letter that is more than 4 written, and that is not allowed. Wrong letters: " . implode(',', array_keys($filteredInput));
} else {
echo "All good";
}
}
checkLetterOccurence('aaaAA');

示例

最新更新