How to find string length without using build-in function strlen()?

This kind of question is sometimes looks funny! but you know this is asked many times in Technical Interview Questions!!.

Yes, I think if you are here then you also crossed the situation what i had in my life!.
If you don’t lets take this time to learn something useful and new which will guide you in the future interviews!

There are plenty of ways to do this!. The first one I’m going to show is the one which is not used any of the build-in string function but it is limted too!.

1st way (without using any string function):


function mystrlen($str)

{
$count = 0;
for($i=0; $i<1000000; $i++)
{
if(@$str[$i] != "")$count++;
else break;
}
return $count;
}

echo mystrlen("this is really useful");

2nd way (using a string function):


$string = "this is too great";
$strlen = count(str_split($string));
echo $strlen;

I hope this helps you in many places thanks!

4 thoughts on “How to find string length without using build-in function strlen()?

    1. This is the best solution I came with so far. It is also language agnostic:
      function findStringLength($string) {
      $length = 0;
      $lastStringChar1 = ‘1’;
      $lastStringChar2 = ‘2’;

      $string1 = $string . $lastStringChar1;
      $string2 = $string . $lastStringChar2;

      while ($string1[$length] != $lastStringChar1 || $string2[$length] != $lastStringChar2) {
      $length++;
      }

      return $length;
      }

Leave a Reply

Theme: Overlay by Kaira
Agurchand