0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「複数形への変換」を解くために : part1

Last updated at Posted at 2025-11-04

今回は paiza の「「複数形への変換」を解くために : part1」の問題に挑戦!


🧩 問題概要

  • 英単語がいくつか与えられる。
  • それぞれの単語に対して、末尾に「s」 を付けて
    複数形に変換し、出力するプログラムを作る。

📥 入力の形式

N
a_1
a_2
...
a_N
  • 1行目:単語の数 N(1〜10)
  • 2行目以降:変換したい英単語が1つずつ与えられる
    (全て小文字のアルファベット)

📤 出力の形式

  • 各単語の末尾に “s” を付けて出力する
  • 出力は N行 にわたる
    (入力順に、1単語につき1行)



入力例:

3
dog
cat
pig

出力例:

dogs
cats
pigs






✅ OK例:

const rl = require('readline').createInterface({ input: process.stdin });

const lines = [];

rl.on('line', (input) => lines.push(input));

rl.on('close', () => {
   const N = Number(lines[0]);
   const a = lines.slice(1);
  
   for (let i = 0; i < N; i++) {
       const word = a[i];
       console.log(word + 's');
   }
});

🪄 ポイント

1️⃣ 入力処理の基本

  • readline + lines.push() + on('close') の3ステップで、複数行入力を安全に処理できる。

2️⃣ データの分割

  • lines[0] → 単語数(N
  • lines.slice(1) → 実際のデータ部分

3️⃣ forループで順に処理

  • 入力された単語を1つずつ取り出し、
  • 加工(末尾に "s" を付与)して出力。

4️⃣ console.logで1行ずつ出力

  • paizaでは「余計な出力をしない」が重要。
  • 文字列連結だけ行えばOK。




🧱 文字を付け足す基本構文

✅ ① 「+」演算子で結合

const plural = word + 's';

これが一番シンプルで早い方法かな。

たとえば:

let word = "dog";
console.log(word + "s"); // → "dogs"

このとき、元の word は変化せず、
新しい文字列 "dogs" が生成されている。



✅ ② テンプレートリテラル(バッククォート)

const plural = `${word}s`;

テンプレート文字列(バッククォート `)を使うと、
埋め込みがわかりやすくなる。

例:

let word = "cat";
console.log(`${word}s`); // → "cats"

⚡ 読みやすく、文字列中に他の要素を混ぜたいときに便利。



✅ ③ concatメソッドを使う

const plural = word.concat('s');

結果は同じで "dogs" が返る。
ただし、+ や テンプレートリテラルのほうが主流で可読性も高いかも。






📝 まとめ

  • JavaScriptで文字列の末尾に文字を付け足すには
    +」演算子 を使うのが最も基本的。
  • ほかに テンプレートリテラル や concat() も可能。
  • この問題では「console.log(word + 's');」がまさに「文字を付け足して出力」する部分。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?