如何编写一个函数来给出传递给它的字符的编号?
例如,如果函数名称是GetCharacterNumber,并且我将B传递给它,那么它应该为我提供2
GetCharacterNumber("A") // should print 1
GetCharacterNumber("C") // should print 3
GetCharacterNumber("Z") // should print 26
GetCharacterNumber("AA") // should print 27
GetCharacterNumber("AA") // should print 27
GetCharacterNumber("AC") // should print 29有没有可能做到这一点?
发布于 2013-01-16 20:44:12
效率不是很高,但可以完成工作:
function get_character_number($end)
{
$count = 1;
$char = 'A';
$end = strtoupper($end);
while ($char !== $end) {
$count++;
$char++;
}
return $count;
}
echo get_character_number('AA'); // 27这是因为当你得到像$char = 'A'和$char++这样的东西时,它会变成'B',然后变成'C','D',…'Z','AA','AB‘等等。
注意,$end越长,这将变得越慢。对于超出'ZZZZ‘(475254次迭代)的任何东西,或者如果你需要很多这样的查找,我不推荐这样做。
性能更好的替代方案是
function get_character_number($string) {
$number = 0;
$string = strtoupper($string);
$dictionary = array_combine(range('A', 'Z'), range(1, 26));
for ($pos = 0; isset($string[$pos]); $pos++) {
$number += $dictionary[$string[$pos]] + $pos * 26 - $pos;
}
return $number;
}
echo get_character_number(''), PHP_EOL; // 0
echo get_character_number('Z'), PHP_EOL; // 26
echo get_character_number('AA'), PHP_EOL; // 27发布于 2013-01-16 20:34:04
有一个名为ord的函数可以给出字符的ASCII码。
ord($chr) - ord('A') + 1为您提供一个字符的正确结果。对于较长的字符串,可以使用循环。
<?php
function GetCharacterNumber($str) {
$num = 0;
for ($i = 0; $i < strlen($str); $i++) {
$num = 26 * $num + ord($str[$i]) - 64;
}
return $num;
}
GetCharacterNumber("A"); //1
GetCharacterNumber("C"); //3
GetCharacterNumber("Z"); //26
GetCharacterNumber("AA"); //27
GetCharacterNumber("AC"); //29
GetCharacterNumber("BA"); //53
?>发布于 2013-01-16 20:36:11
使用range和strpos:
$letter = 'z';
$alphabet = range('a', 'z');
$position = strpos($alphabet, $letter);对于双字母(例如zz),您可能需要使用自定义函数创建自己的字母表:
$alphabet = range('a', 'z');
$dictionary = range('a','z');
foreach($alphabet AS $a1){
foreach($alphabet AS $a2) {
$dictionary[] = $a1 . $a2;
}
}然后用$dictionary代替$alphabet。
https://stackoverflow.com/questions/14358548
复制相似问题