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?

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

Last updated at Posted at 2025-11-06

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


🧩 問題概要

🎯 目的

英単語の末尾を判定して、

  • "f" または "fe" で終わる単語 → 「f / fe」を削除して「ves」を付ける
  • それ以外の単語 → 末尾に「s」を付ける

というルールで複数形を作るプログラムを作成する。


📥 入力形式

N
a_1
a_2
...
a_N
  • N: 単語の数(1〜10)
  • a_i: 変換対象の英単語(長さ2〜20)

📤 出力形式

  • 各単語をルールに従って複数形にして出力。



入力例:

7
box
photo
axis
dish
church
leaf
knife

出力例:

boxs
photos
axiss
dishs
churchs
leaves
knives






✅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[end] === 'f') {
            console.log(word.slice(0, end) + 'ves')
        } else if (word.slice(end-1) === 'fe') {
            console.log(word.slice(0, end-1) + 'ves');
        } else {
            console.log(word + 's');
        }
    }
});

🧭 コードの流れ

  1. readlineで入力を受け取る準備
    • 標準入力から行ごとに受け取って lines 配列に格納。
  2. 入力がすべて終わったら処理を開始
    • rl.on('close', ...) の中でメイン処理を実行。
  3. 1行目から単語数 N を取得
    • const N = Number(lines[0]);
  4. 2行目以降に単語リストを取得
    • const a = lines.slice(1);
  5. for文で各単語を1つずつ処理
    • const word = a[i];
    • const end = word.length - 1; → 最後の文字の位置。
  6. 末尾を判定して変換
    • 末尾が "f" → word.slice(0, end) + "ves"
    • 末尾が "fe" → word.slice(0, end - 1) + "ves"
    • それ以外 → word + "s"
  7. 結果を出力
    • console.log()` で複数形を1行ずつ出力。






📝 学習のまとめ

① 文字列の一部削除:slice() を使う

  • word.slice(0, end) → 最後の1文字を削除
  • word.slice(0, end - 1) → 最後の2文字("fe")を削除

② 末尾の判定

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

③ 条件分岐で特定のパターンを処理

  • まず "f" / "fe" の特別ルールを判定し、
  • それ以外は通常の "s" 追加処理に回す。

④ 「文字を追加」と「文字を削除」を組み合わせる
→ "leaf" → "lea" + "ves"
→ "knife" → "kni" + "ves"

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?