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

配列と文字列の2段階アクセスでラクする!

Posted at

Paizaの配列系問題にまた挑戦!
今回は「配列の中の文字列」から、さらに「その中の1文字」を抜き出すという、ちょっとだけややこしい問題。


🧩問題概要

M 個の文字列が並んでいる配列があり、その N 番目の文字列の L 番目の文字を取り出せ」


入力例:

3 5 2
abc def ghi jkl mno

出力例:

h



🔁 ループを使ったコード例

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

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

rl.on('close', () => {
    const [N, M, L] = lines[0].split(' ').map(Number);
    const words = lines[1].split(' ');

    let targetWord = '';
    for (let i = 0; i < M; i++) {
        if (i === N - 1) {
            targetWord = words[i];
            break;
        }
    }

    let resultChar = '';
    for (let j = 0; j < targetWord.length; j++) {
        if (j === L - 1) {
            resultChar = targetWord[j];
            break;
        }
    }

    console.log(resultChar);
});

🔍 解説:

  • 最初のループで、N 番目の文字列(0-indexed で N-1)を探す。
  • 次のループで、その文字列の L 番目の文字(0-indexedで L-1)を探す。
  • 両方とも break を使って、条件を満たしたらすぐループを抜けるようする。



📌二重インデックスで取得バージョン

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

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


rl.on('close',()=>{
    const [N,M,L] = lines[0].split(' ').map(Number);
    const arr = lines[1].split(' ');
    
    console.log(arr[N-1][L-1]);
})

文字列も配列のようにインデックスでアクセス可能

JavaScriptでは、文字列も配列のようにインデックスでアクセス可能なので、以下のように直接文字を取り出せる

const str = "hello";
console.log(str[1]); // => "e"

✅ ポイントまとめ:

  • 文字列[strIndex] でその位置の文字を取得できる(0-indexed)-
  • split'') で配列に変換する必要はない。
  • strings[N – 1][L – 1] のように、二重インデックスで「 N 番目の文字列の L 番目の文字」が直接取れる。



気づきメモ

  • split('') しなくても文字列はインデックスで直接アクセスできる。
  • ループを使うと処理がわかりやすく見えるけど、今回は不要だった。



✍️まとめ

この問題、簡単だけど「どう書くか」がポイントだった!

split'') を使うと文字列を文字の配列に変換できるけど、文字を取得するだけなら不要みたい。
「文字の並びを変更したい」といった「操作」をする場合には配列にする必要がある!




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

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