如何找到字符串中选定字符的最长连续序列的长度?
我想做的是看看 0 是否在这样的字符串中出现五次或更多次
“111010110101010000010010100000000000111”
我需要的函数将接受一个字符串和一个字符,在上面的示例中,对于字符 0 返回 11
提前非常感谢各位大师:)
最佳答案
我想应该有一种更有效的方法来实现这一点,也许使用正则表达式,但是,这仍然是我带来的
function howmanytimes($str,$char){
$maxcount=0;
$thiscount=0;
for($i=0;$i<strlen($str);$i++){
if(substr($str,$i,1)==$char){
$thiscount++;
if($thiscount>$maxcount) $maxcount=$thiscount;
}else $thiscount=0;
}
return $maxcount;
}
希望有帮助!
编辑:如果您希望它只检查字符是否连续出现超过 X 次,有一种更有效的方法可以实现这一点。如果所选字符出现超过 X 次,此函数将返回 true,否则返回 false。
function Xtimes($str,$char,$howmanytimes){
$maxcount=0;
$thiscount=0;
for($i=0;$i<strlen($str);$i++){
if(substr($str,$i,1)==$char){
$thiscount++;
if($thiscount>$maxcount){
if($thiscount==$howmanytimes+1){return true;}
$maxcount=$thiscount;
}
}else $thiscount=0;
}
return false;
}
关于php - 查找字符串中选定字符的最长连续序列的长度(PHP)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26133134/