最終課題:テキストパイプラインを移植する
Coddyの「C++開発者向けPHP」コースのレッスン 47/48。
チャレンジ
簡単入力は文字列のリストです。このタスクで提供されているソース参照プログラムを移植してください。abbreviations は空文字列を取り除き、残った各文字列の最初の ASCII 文字を取得して大文字にし、ドットで連結します。順序はそのまま保持し、空でない文字列がない場合は none を返します。入力はすべて ASCII です。
提供されている main スクリプトは、標準入力から JSON 値を1つ読み取り、指定された公開 API を確認して、結果を出力します。出力せずにモジュール宣言を実装してください。ランチャーを置き換えたり、モジュールから入力を読み取ったりしないでください。入力は指定された型と範囲を満たしています。
Functions.phpを編集してください。main.phpはロックされたエントリーファイルです。依存ファイルは相対ファイル名を使ってrequire_once __DIR__で読み込みます。
C++の参照プログラム
#include <iostream>
#include <string>
#include <vector>
std::string abbreviations(const std::vector<std::string>& words) {
std::string result;
bool found=false;
for(const auto& word:words) {
if(word.empty()) continue;
if(found) result.push_back('.');
char first=word.front();
if(first>='a' && first<='z') first=static_cast<char>(first-'a'+'A');
result.push_back(first);
found=true;
}
return found ? result : "none";
}
int main() { std::cout<<abbreviations({"red","","green","blue"})<<"\n"; }
自分で試してみよう
<?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オンラインコンパイラ