首页 > 解决方案 > PHP 无法断言两个字符串相等

问题描述

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

指令是:

而且我已经制作了这样的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

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

标签: php

解决方案


如果一个字符是a,array_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);
}

推荐阅读