簡體   English   中英

PHP 斷言兩個字符串相等失敗

[英]PHP Failed asserting that two strings are equal

我正在 codewars.com 中進行訓練測試,

指令是:

  • 在這個 kata 中,給定一個字符串,您需要用字母表中的 position 替換每個字母。
  • 如果文本中的任何內容不是字母,請忽略它並且不要返回它。 “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

請問有人可以幫忙解決嗎? 並告訴我為什么它顯示錯誤的詳細信息?

如果一個字符是aarray_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);
}

只是一種替代方法,無需搜索“字母”來檢查字符。 使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM