PHP bir dize N attırın

4 Cevap php

Ben sol N kez bir dize döndürmek için bir yol arıyorum. İşte bazı örnekler:

Dize olsun 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.

4 Cevap

Bunun için standart bir fonksiyondur ancak kolayca uygulanır.

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

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

Sen döndürmek için karakter sayısı için isteğe bağlı bir parametre eklemek için bu genişletmek olabilir.

Burada sağ ve sol, ne olursa olsun giriş dizesi uzunluğu keyfi kaymasını sağlayan bir çeşididir:

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

Bu kodu kullanın

<?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;
    }
    ?>

Ayrıca N böyle dizeleri döndürülebilir alabilirsiniz.

$str = "Vijaysinh";
$arr1 = str_split($str);
$rotated = array();
$i=0;


    foreach($arr1 as $a){
        $t = $arr1[$i];
        unset($arr1[$i]);
        $rotated[] = $t.implode($arr1);
        $arr1[$i] = $t;
        $i++; 
    }
    echo "<pre>";print_r($rotated);exit;