Today, almost all modern languages have their own built-in methods to reverse a string. For example, PHP have strrev($stringtoreverse) while ruby has stringtoreverse.reverse utility to reverse the string. Availability of these methods prohibit us to think about the small-small logic behind these methods. Sometimes, it may be the harmful for developer community too. Following is the code in PHP to reverse a string:
<?php
echo str_rev('abcxyz'); //called the method
function str_rev($stringtoreverse) //strrev is built-in method. So, str_rev is defined as custom function
{
$revstr=''; //initially empty string
$len=strlen($stringtoreverse);
for($i=$len-1;$i>=0;$i--)
{
$revstr.=substr($stringtoreverse,$i,1); //concat each character returned by substr method
}
return $revstr;
}
?>
Please feel free to make your valuable comment.
No comments:
Post a Comment
Thanks for your valuable comments.