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?

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

Last updated at Posted at 2025-11-05

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

特定の語尾パターンのときのルールを追加するという次のステップを解いていく!


🧩 問題概要

  • 英単語を複数形に変換するプログラムを作る。
  • ただし今回は単純に「s」を足すだけではなく、
    特定の語尾パターンのときは「es」を足す というルールを追加。

◯ 条件:変換ルール

  • 末尾が s, sh, ch, o, x :「es」 を付ける
  • それ以外:「s」 を付ける

📥 入力

N
a_1
a_2
...
a_N
  • 1行目:単語の数 N
  • 2行目以降:変換対象の英単語 a_i(小文字、長さ2〜20)

📤 出力

  • 各単語を複数形に変換して N行 出力。



入力例:

7
box
photo
axis
dish
church
leaf
knife

出力例:

boxes
photoes
axises
dishes
churches
leafs
knifes






✅ 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];
        const end = word.length - 1;
        
        if (word.slice(end-1) === 'sh' || word.slice(end-1) === 'ch') {
            console.log(word + 'es');
        } else if (word[end] === 's' || word[end] === 'o' || word[end] === 'x') {
            console.log(word + 'es');
        } else {
            console.log(word + 's');
        }
    }
});

🧭 コードの流れ

  1. 入力を受け取る準備
    • readline モジュールで、標準入力からデータを読む準備をする。
  2. 入力行を配列に保存
    • 入力があるたびに lines.push(input) で配列 lines に1行ずつ追加。
  3. 全ての入力が終わったら処理開始
    • rl.on('close', () => { ... }) の中で、全行の入力を処理。
    • 1行目(N)を数値に変換
      const N = Number(lines[0]);
      → 変換すべき英単語の数を取得。
    • 残りの行(単語)を取り出す
      const a = lines.slice(1);
      → 実際に処理する単語リスト。
  4. for文で1つずつ単語を処理
    • for (let i = 0; i < N; i++) { ... }
  5. 各単語の末尾を確認する準備
    • const end = word.length - 1;
      → 最後の文字の位置を計算。
  6. 末尾のパターンを判定
    • 末尾2文字が "sh" または "ch""es" を付ける
    • 末尾1文字が "s", "o", "x""es" を付ける
    • それ以外 → "s" を付ける
  7. 結果を出力
    console.log() で複数形を表示。






🗒️ まとめ

① 入力処理の基本

  • readline を使って全行を配列 lines に読み込み、
  • 1行目を単語数、2行目以降を単語リストとして扱う。

② 文字列の末尾を取り出す方法

  • word[word.length - 1] → 最後の1文字を取得
  • word.slice(end - 1) → 最後の2文字を取得

③ 条件分岐でルールを実装

  • "sh""ch" のような2文字末尾は slice() で判定
  • "s", "o", "x" は 1文字末尾 で判定

④ 文字の追加(複数形)

  • 条件に応じて word + 'es' または word + 's'

⑤ 出力

  • console.log() で1単語ずつ出力
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?