最终挑战:移植文本处理流水线
Coddy 面向 C 开发者的 PHP 课程的第 47 课,共 48 课。
挑战
简单输入是一个字符串列表。请移植本任务中提供的参考源程序:abbreviations 移除空字符串,获取每个剩余字符串的第一个 ASCII 字符,将其转换为大写,并用点号连接。保持顺序;如果没有非空字符串,则返回 "none"。所有输入均为 ASCII。
提供的主脚本从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。请在不打印任何内容的情况下实现模块声明;不要替换启动程序或从模块中读取输入。输入满足规定的类型和范围限制。
编辑 Functions.php。main.php 是被锁定的入口文件。依赖项使用带有相对文件名的 require_once __DIR__。
C 参考程序
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
struct Text { const unsigned char *bytes; size_t length; };
struct Result { unsigned char *bytes; size_t length; };
/* Lengths preserve all ASCII bytes, including an embedded zero byte. */
static int abbreviations(const struct Text *words, size_t count, struct Result *out) {
if (count > (SIZE_MAX - 5) / 2) return 0;
unsigned char *result = malloc(count * 2 + 5);
if (result == NULL) return 0;
size_t length = 0;
for (size_t i = 0; i < count; ++i) {
if (words[i].length == 0) continue;
if (length != 0) result[length++] = '.';
unsigned char first = words[i].bytes[0];
if (first >= 'a' && first <= 'z') first = (unsigned char)(first - 'a' + 'A');
result[length++] = first;
}
if (length == 0) { memcpy(result, "none", 4); length = 4; }
*out = (struct Result){result, length};
return 1;
}
int main(void) {
const struct Text words[] = {
{(const unsigned char *)"red", 3}, {(const unsigned char *)"", 0},
{(const unsigned char *)"green", 5}, {(const unsigned char *)"blue", 4}
};
struct Result result;
if (!abbreviations(words, 4, &result)) return 1;
fwrite(result.bytes, 1, result.length, stdout);
putchar('\n');
free(result.bytes);
return ferror(stdout) ? 1 : 0;
}
亲手试试
<?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";
面向 C 开发者的 PHP中的所有课
自己练习: PHP 在线编译器