views:

183

answers:

5

I'm looking for a way to rotate a string to the left N times. Here are some examples:

Let the string be abcdef

  • if I rotate it 1 time I want bcdefa
  • if I rotate it 2 time I want cdefab
  • if I rotate it 3 time I want defabc
  • .
  • .
  • If I rotate the string its string length times, I should get back the original string.
+2  A: 
function rotate_string ($str, $n)
{
    while ($n > 0)
    {
        $str = substr($str, 1) . substr($str, 0, 1);
        $n--;
    }

    return $str;
}
Andy E
+1  A: 

There is no standard function for this but is easily implemented.

function rotate_left($s) {
  return substr($s, 1) . $s[0];
}

function rotate_right($s) {
  return substr($s, -1) . substr($s, 0, -1);
}

You could extend this to add an optional parameter for the number of characters to rotate.

cletus
+7  A: 
 $rotated = substr($str, $n) . substr($str, 0, $n);
stereofrog
+1..lot simpler :)
codaddict
Thanks stereoforg. This works.
gameover
Wouldn't work if `$n` is greater than the length of the string though, would it?
Svish
This will return the original string if $n > string length.
Gordon
@Gordon, Svish: My N will never exceed string length.
gameover
@gameover: ok, then I suppose it doesn't matter.
Svish
+1 for simplicity. For $n > strlen($str) you can do $n %= strlen($str) and then the solution provided by stereofrog.
Ch4m3l3on
@Ch4m3l3on See my alternative below for the modulo version
Gordon
@Gordon Yeah, I haven't noticed that, sorry. Anyway, that's the proper way to do it :).
Ch4m3l3on
+1  A: 

Here is one variant that allows arbitrary shifting to the left and right, regardless of the length of the input string:

function str_shift($str, $len) {
    $len = $len % strlen($str);
    return substr($str, $len) . substr($str, 0, $len);
}

echo str_shift('abcdef', -2);  // efabcd
echo str_shift('abcdef', 2);   // cdefab
echo str_shift('abcdef', 11);  // fabcde
Gordon
A: 

Use this code

<?php
    $str = "helloworld" ;
    $res = string_function($str,3) ;
    print_r ( $res) ;
    function string_function ( $str , $count )
    {
    $arr = str_split ( $str );
    for ( $i=0; $i<$count ; $i++ )
    {
      $element = array_pop ( $arr ) ;
      array_unshift ( $arr, $element ) ;
    }
    $result=( implode ( "",$arr )) ;
    return $result;
    }
    ?>
pavun_cool