最終課題:テキストパイプラインを移植する
Coddyの「C開発者のためのPHP」コースのレッスン 47/48。
チャレンジ
簡単入力は文字列のリストです。このタスクで提供されている参照プログラムを移植してください。`abbreviations` は空文字列を取り除き、残りの各文字列の最初の ASCII 文字を取得して大文字に変換し、ドットで結合します。順序は保持してください。空でない文字列が存在しない場合は `"none"` を返します。すべての入力は ASCII です。
提供されたメインスクリプトは、標準入力から 1 つの 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オンラインコンパイラ