2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Paizaの「指定位置の文字を置換」問題で、またインデックスの罠にやられました(´;ω;`) 今回は文字列の書き換えの問題について解説!


問題概要

文字列 S、整数 i(位置)、文字 c が与えられる

Si文字目 を c に置き換えて出力せよ

入力例:

ABCDEFGHIJKLMNOPQRSTUVW&XYZ
16 !

出力例:

ABCDEFGHIJKLMNO!QRSTUVW&XYZ



NGコード:ズレ

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


rl.on('line', input => lines.push(input));
rl.on('close',()=>{
    const S = lines[0];
    const [i,c] = lines[1].split(' ');
    
    const result = S.slice(0,Number(i)) + c + S.slice(Number(i)+1);
    
    console.log(result);
});

🔻 i は 1-based(1文字目が1)なのに、JavaScriptの .slice() は 0-based。
つまり「1引く」必要あり!


✅ OKコード:ズレ補正

const index = Number(i) - 1;
const result = S.slice(0, index) + c + S.slice(index + 1);

🔧 .slice()は [start, end) の半開区間。end は含まないので index + 1 を使う。


✅ 配列化アプローチ:さらに読みやすく

const chars = S.split('');
chars[index] = c;
console.log(chars.join(''));
  • .split('') → 配列に

  • chars[index] = c → 置換

  • .join('') → 再び文字列に

👉 直感的!文字列の書き換えには実はこっちの方が見やすくて安全かも。


💡 技術メモまとめ

  • JSのインデックスは 0-based、でも入力が 1-based なら -1 する
  • .slice(start, end) の end は含まれない(=半開区間)
  • .split().join() の編集パターンは、柔軟かつ安全




僕の失敗談(´;ω;`)と解決法🐈

2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?