최종: 텍스트 파이프라인 이식하기
Coddy의 C 개발자를 위한 PHP 코스 레슨. 48개 중 47번째.
챌린지
쉬움입력은 문자열 목록입니다. 이 과제에 제공된 소스 레퍼런스 프로그램을 포팅하세요: abbreviations는 빈 문자열을 제거하고, 남은 각 문자열의 첫 번째 ASCII 문자를 가져와 대문자로 변환한 뒤 점(dot)으로 연결합니다. 순서를 유지하세요. 비어 있지 않은 문자열이 없으면 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 컴파일러