How can strlen () be implemented without using php internal functions?

Source: Internet
Author: User
How can strlen () be implemented without using php internal functions? How can strlen () be implemented without using php internal functions?

Reply content:

How can strlen () be implemented without using php internal functions?

function mystrlen($str){   $i = 0;   while(1)if(!isset($str[$i++]))return $i-1;}

The efficiency is not high, so it can be improved. For example, the greatest coordinate can be found using isset in the binary method.

This is a little more efficient.

function mystrlen($str){   $i = -1;   while(1) if(!isset($str[++$i])) return $i;}

Function mystrlen ($ str) {$ size = 1024; // value range of 1024 for each test: $ count = 0; // number of times that the test meets the length $ length = $ size * $ count-1; // currently, you can determine the length of the string while (isset ($ str [$ length + $ size]) {// test, 2047, 3071,4095 ...... $ Count = $ count + 1; $ length = $ length + $ size;} $ low = 0; // Binary Search bottom boundary $ high = $ size-1; // The second part searches for the upper boundary while ($ low <= $ high) {$ mid = floor ($ low + $ high)/2 ); if (isset ($ str [$ length + $ mid]) &! Isset ($ str [$ length + $ mid + 1]) {return $ length + $ mid + 1;} if (! Isset ($ str [$ length + $ mid]) {$ high = $ mid-1;} if (isset ($ str [$ length + $ mid]) {$ low = $ mid + 1 ;}}}

// The method in the other answers above, a 2 m string needs to be cyclically 2 million times.
// This is not the best solution, but it also reduces the 2 m string loop to more than 2000 times.
// PHP saves the string with a length when saving it. You don't have to worry about it. You can use native functions to retrieve it easily. Why.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.