strlen()完全不用php内部函数如何实现?

WBOY
Release: 2016-06-06 20:42:49
Original
959 people have browsed it

strlen()完全不用php内部函数如何实现?

回复内容:

strlen()完全不用php内部函数如何实现?

<code>function mystrlen($str){
   $i = 0;
   while(1)if(!isset($str[$i++]))return $i-1;
}
</code>
Copy after login

效率不高,可以改进下,例如使用二分法用isset找到最大的坐标

改成這樣效率更高了一點

<code>function mystrlen($str){
   $i = -1;
   while(1) if(!isset($str[++$i])) return $i;
}
</code>
Copy after login

<code>function mystrlen($str){
   $size = 1024;//每次试探1024的范围
   $count = 0;//试探并且满足长度的次数
   $length = $size * $count - 1;//当前可以确定字符串具有的长度
   while( isset( $str[ $length + $size ] ) ){//依次试探1023,2047,3071,4095……
      $count = $count + 1;
      $length = $length + $size;
   }
   $low = 0;//二分查找下边界
   $high = $size - 1;//二分查找上边界
   while($low </code>
Copy after login

//上面其它的答案里的方法,一个2M的字符串要循环200万次,简直了。
//我这种不是最佳方案,不过也将2M的字符串的循环减少到了2000多次。
//PHP保存字符串的时候本来就保存有长度,根本不用这么费事,用原生的函数轻松就能取出来,何必。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template