我不知道如何创建一个函数来计算一行中相同字母的重复次数是多少次?
例如:avcdddjrg返回1,aaargthbbb返回2
我可以检测到一行中是否有3个相同的字符,但无法弄清楚如何计算它
$input = 'hellooommm';
if (preg_match('/(.)\1{2}/', $input)) {
return 1;
}else {
return 0;
}
谢谢
答案 0 :(得分:1)
使用preg_match_all()
,如下所示:
$input = 'hellooommm';
$n = preg_match_all('/(.)\1{2}/', $input);
if ($n !== false) {
echo "$n matches found", PHP_EOL;
} else {
echo "an error occurred when calling preg_match_all()", PHP_EOL;
}
答案 1 :(得分:1)
@ hek2mgl上面的答案很简单,并且使用正则表达式雄辩地解决了这个问题。但我觉得你可能会从逻辑上对此进行更深入的讨论。您可以使用的另一种方法是迭代字符并计算重复次数,如下所示:
function countGroupsOfThree($str) {
$length = strlen($str);
$count = 1;
$groups = 0;
for ($i = 0; $i < $length; $i++){
// is this character the same as the last one?
if ($i && $str[$i] === $str[$i-1]) {
// if so, increment the counter
$count++;
// is this the third repeated character in a row?
if ($count == 3) {
// if so, increment $groups
$groups++;
}
} else {
// if not, reset the counter
$count = 1;
}
}
return $groups;
}
$str = 'aaavgfwbbb3ds';
echo countGroupsOfThree($str);
输出: 2
在宏观方案中,这个功能可能不是很有用,但希望它能说明一些关键概念,这些概念可以帮助你在将来解决这个问题。