【问题标题】:PHP custom encoding function is not giving required resultPHP自定义编码功能没有给出所需的结果
【发布时间】:2017-10-11 11:02:28
【问题描述】:

我正在尝试在 PHP 中编写一个函数,它可以根据给定的偏移量将字符串转换为编码的字符串。

例如: 如果偏移量是2,输入是c,那么输出是e 同样,如果偏移量是5,输入是X,那么输出是c

function encode($char,$offset)
{
 $char_list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 $_offset = strpos($char_list,$char) + $offset;

 if($offset > strlen($char_list )){
  $_offset = _$offset  - $offset;
 }
 return $char_list[$_offset];
}

要求的结果:

encode("a",0) // must returns a
encode("c",5) // must returns h
encode("X",9) // must returns g

【问题讨论】:

  • 你的问题是......?
  • @Twinfriends,修正算法
  • PHP Caesar cipher的可能重复
  • if ....代替$_offset = $_offset % strlen($char_list);
  • $_offset = _$offset - $offset; 为什么是_$offset 而不是$_offset

标签: php algorithm character-encoding


【解决方案1】:

if 块内新偏移量的计算不正确,你应该减去字符串的长度,而不是偏移量。但最好使用modulo operator

function encode($char,$offset) {
    $char_list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $_offset = strpos($char_list,$char) + $offset;
    $_offset = $_offset % strlen($char_list);
    return $char_list[$_offset];
}

【讨论】:

  • 你能解释一下 % 符号在这里的作用吗?
  • 就是modulo operator,所以只要左边的值大于右边的值,就按右边的值减少,直到小于右边的值。否则,就是整数除法后的余数。
猜你喜欢
  • 2015-03-04
  • 2013-10-14
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
相关资源
最近更新 更多