PHP自定义编码功能没有给出所需的结果
我想在PHP中编写一个函数,以便按照给定的偏移量将字符串转换为编码的函数。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
计算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](http://php.net/manual/en/language.operators.arithmetic.php),所以无论何时左边的值大于右边的值,它都会被减少正确的值,直到它小于右边的值。否则,它是整数除法后的余数。 – trincot
而你的问题是......? – Twinfriends
@Twinfriends,修复算法 –
[PHP Caesar cipher]的可能重复(https://stackoverflow.com/questions/21177443/php-caesar-cipher) – Profit