PHP 断言两个字符串相等失败

时间:2021-03-14 14:29:05

标签: php

我正在 codewars.com 上进行训练测试,

指令是:

  • 在这个 kata 中,你需要给一个字符串,用它在字母表中的位置替换每个字母。
  • 如果文本中的任何内容不是字母,请忽略它并且不要返回它。 “a”=1,“b”=2。

我已经制作了这样的 PHP 脚本

<?php
function alphabet_position($string) 
{
    $lower = strtolower($string);
    $alphabet = range("a", "z");
    $result = "";

    for ($i=0; $i<strlen($lower); $i++)
    {
      $filter = array_search($lower[$i], $alphabet);
      if ($filter)
        {
          $result .= $filter+1 ." ";
        }
    }
    
    return $result;
}

echo alphabet_position('The sunset sets at twelve o\'clock');
//output 20 8 5 19 21 14 19 5 20 19 5 20 19 20 20 23 5 12 22 5 15 3 12 15 3 11

但是当我提交我的答案时,它包含像

这样的错误
Time: 937msPassed: 0Failed: 1Exit Code: 1
Test Results:
Log
PHPUnit 9.1.1 by Sebastian Bergmann and contributors.
AlphabetPositionTest
testFixed
Failed asserting that two strings are equal.
Expected: '20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'
Actual  : ''
Completed in 23.3161ms

请问有人可以帮忙解决吗?并告诉我为什么显示错误的详细信息?

2 个答案:

答案 0 :(得分:3)

如果字符是 aarray_search() 将返回 0if($filter) 将忽略它,因为 if(0) 为假。因此,您可以使用严格的类型检查来避免该问题。

<?php
function alphabet_position($string) {
    $lower = strtolower($string);
    $alphabet = range("a", "z");
    $parts = [];

    for ($i=0; $i < strlen($lower); $i++)
    {
        $filter = array_search($lower[$i], $alphabet);
        if ($filter !== false){ // always have strict type check as array index can also be 0
            $parts[] = $filter + 1;
        }
    }

    return implode(' ', $parts);
}

答案 1 :(得分:1)

只是一种替代方法,它不必搜索“字母”来检查字符。使用 ord() 给出字符的 ascii 值,这是一个简单的翻译。然后将其偏移 a 的值以给出字符...

function alphabet_position($string)
{
    $lower = strtolower($string);
    $result = "";

    for ($i=0; $i<strlen($lower); $i++)
    {
        if ( $lower[$i] >= 'a' && $lower[$i] <= 'z' )   {
            $result .= (ord($lower[$i]) - ord('a'))+1 ." ";
        }
    }

    return trim($result);
}
相关问题