Menu
CoddyTech

最终挑战:迁移文本处理流水线

Coddy 面向 Go 开发者的 PHP 课程的第 47 课,共 48 课。

challenge icon

挑战

简单

输入是一个字符串列表。请移植本挑战提供的源参考程序:abbreviations 会移除空字符串,取每个剩余字符串的第一个 ASCII 字符,将其转换为大写,并用点号连接。保留原有顺序;如果没有非空字符串,则返回 none。所有输入都是 ASCII。

提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。请实现模块声明,不要打印内容;不要替换启动脚本,也不要从模块读取输入。输入符合指定的类型和范围。

编辑 Functions.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。

Go 参考程序

package main
import ("fmt";"strings")
func abbreviations(words []string)string{
    parts:=make([]string,0,len(words))
    for _,word:=range words{
        if len(word)==0{continue}
        first:=word[0]
        if first>='a' && first<='z'{first-= 'a'-'A'}
        parts=append(parts,string([]byte{first}))
    }
    if len(parts)==0{return "none"}
    return strings.Join(parts,".")
}
func main(){fmt.Println(abbreviations([]string{"red","","green","blue"}))}

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}

$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure(abbreviations(["a","","b"])==="A.B" && abbreviations([])==="none","port pipeline");
echo abbreviations($input),"\n";

面向 Go 开发者的 PHP中的所有课

自己练习: PHP 在线编译器