dongyan6503 2019-04-13 07:29
浏览 86
已采纳

计算ASCII码为3的倍数的字符串中的字符数,而不使用循环或递归

I have the following PHP code which uses foreach and gives the correct count. This is what I tried with loop.

$str = 'hello world';
$cnt = 0;

$arr = str_split($str);
foreach($arr as $val){
  if( ord($val)%3 == 0 ){
   $cnt++;
  }
}
echo 'total count- '.$cnt; //count is 6 here which is correct

Is there a way of doing the same thing in PHP without the use of loops or recursion?

  • 写回答

1条回答 默认 最新

  • dongxian7489 2019-04-13 07:34
    关注

    You can use PHPs inbuilt array functions to do this, but internally they loop over the values themselves so is that valid? One way would be to use array_filter on the results of str_split and then getting the count of the number of values in the resultant array:

    $str = 'hello world';
    $cnt = count(array_filter(str_split($str), function ($v) { return ord($v) % 3 == 0; }));
    echo $cnt;
    

    Output

    6
    

    You can also do something similar with array_reduce (this is most similar to your existing code):

    $cnt = array_reduce(str_split($str), function ($c, $v) { return $c + (ord($v) % 3 == 0 ? 1 : 0); }, 0);
    

    Demo on 3v4l.org

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法