mevr
mevr

Reputation: 1125

Move specific character to right

I need to move a specific character in a string from a specific position to right by specific places. string, position, and places are inputs it can be any value. (Maximum use less number of lines using PHP functions).

$string = 'Peacock';
$position = 2;
$places = 2;

move($string,$position,$places);

function move($string,$position,$places){

$string[($position-1)+$places] = $string[$position-1];
echo $string ; 
}

Expected output is Paceock

Upvotes: 0

Views: 969

Answers (2)

Andy Song
Andy Song

Reputation: 4684

If you do not mind you can modify the string as well.

$string = 'Peacock';
$position = 2;
$places = 2;


function move($string,$position,$places){
  $char = $string[$position-1];
  $string = substr_replace($string, '', $position-1, 1);
  $string = substr_replace($string, $char, $position+$places-1, 0);

  echo $string; 
}

move($string,$position,$places);

Upvotes: 1

GNassro
GNassro

Reputation: 1071

with for loop will be a good solution.

NB: the $position must be start from 1.

<?php
$string = 'Peacock';
$position = 2;
$places = 2;

move($string,$position,$places);

function move($string,$position,$places){
    $keep =  $string[$position-1];
    for($i=0; $i<=$places;$i++){
        $string[($position-1)+$i] = $string[$position+$i];
    }
    $string[$position+$places-1] = $keep;
    echo $string ;
}

Upvotes: 1

Related Questions