Re: reverse string without strrev();
| From: | Robert Cummings | Date: | Thu, 28 Feb 2008 17:46:40 +0000 |
| Subject: | Re: reverse string without strrev(); | ||
| References: | 1 2 3 4 5 6 7 8 9 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-270609@lists.php.net to get a copy of this message | ||
On Thu, 2008-02-28 at 16:26 +0000, Robin Vickery wrote:
> On 28/02/2008, Robert Cummings <robert@interjinn.com> wrote:
> >
> > There's always a tradeoff between speed and memory. Here's the low
> > memory version:
> >
> > <?php
> >
> > $str = '1234567';
> > str_reverse_in_place( $str );
> > echo 'Reversed: '.$str."\n";
> >
> > function str_reverse_in_place( &$str )
> > {
> > $a = 0;
> > $z = strlen( $str ) - 1;
> >
> > while( $a < $z )
> > {
> > $t = $str[$a];
> > $str[$a] = $str[$z];
> > $str[$z] = $t;
> >
> > ++$a;
> > --$z;
> > }
> > }
> >
> > ?>
>
>
> every byte counts :-)
>
> function str_reverse_in_place( &$str )
> {
> $a = -1;
> $z = strlen($str);
>
> while( ++$a < --$z )
> {
> $str[$a] = $str[$a] ^ $str[$z];
> $str[$z] = $str[$a] ^ $str[$z];
> $str[$a] = $str[$a] ^ $str[$z];
> }
> }
>
Nicely done.
Cheers,
Rob.
--
.------------------------------------------------------------.
| InterJinn Application Framework - http://www.interjinn.com
|
:------------------------------------------------------------:
| An application and templating framework for PHP. Boasting |
| a powerful, scalable system for accessing system services |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for |
| creating re-usable components quickly and easily. |
`------------------------------------------------------------'