AdamLin0708 AdamLin0708 - 1 month ago 14
PHP Question

php character increment for 'Y' and ++ 2 times

I have a php question here. I have 2 inputs, ($s, $n), $s represents a string and $n is a integer. And the question is: "shift each character in $s $n position".

e.g $s = "AA", $n = 2, then output is "CC"

I have a little problem here, if $s = "YY", $n = 2, it will output "aaaa", but I

want the output to be "aa", how should I fix my code?

below is my code:

$words = str_split($s);

for($i=0;$i<count($words);$i++){

if($words[$i] == " ") {
//if space
continue;
}
else{
for($y=0;$y<$n;$y++)
$words[$i] = ++$words[$i];
}
}

$ans = join("", $words);

print("$ans\n");


Thanks a lot.

Answer Source

This solution may be not 100% true. Or there may be better solution. But I have try to get substring from string if length is more than original length

<?php
$s = "YY";
$n = 2;
$words = str_split($s);            
for($i=0;$i<count($words);$i++){

  if($words[$i] == " ") {
    //if space
    continue;
  }                    
  else{
    for($y=0;$y<$n;$y++){
      $cur_len = strlen($words[$i]);
      $words[$i] = ++$words[$i];
      $new_len = strlen($words[$i]);
      if($new_len > $cur_len)
        $words[$i] = substr($words[$i], 0,$cur_len);      
    }
  }      
}

$ans = join("", $words);

print("$ans\n");