php - 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
请问有人可以帮忙解决吗?并告诉我为什么它显示错误的详细信息?
解决方案
如果一个字符是a
,array_search()
将返回0
并if($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);
}
推荐阅读
- javascript - 嵌套动态反应相同的组件
- graphql - React Apollo 中本地解析器的执行顺序是什么?
- html - 如何在 Font Awesome 5 中水平对齐分层图标?
- c++ - 删除动态内存是如何真正起作用的?
- php - 从 PHP 使用 sqlsrv 时登录失败
- php - Laravel:如何使用 Eloquent 获取关系列的总和
- linux - 根据 bash 中给出的键进行排序
- android - Firebase动态链接同步?
- sql-server - 如何将格式为 MM-DD-YYYY 的日期更改为在 SSIS 中的 MM 和 DD 中没有前导零?
- nginx - 通过 nginx 提供静态文件时如何修复 404 错误