2:00am, Writing code

Roughly coding. Posted from Berlin.

Javascriptで文字列中に出現する各文字を数える

プログラミング問題などでありがちな、ある文字列内の任意の文字の出現数をカウントするという課題。Javascriptだとこんな感じに書ける。

function countCharInStr(str, chara) {
  const counts = {};
  for (let c of str) {
    counts[c] = c in counts ? counts[c] + 1 : 1;
  }
  return chara in counts ? counts[chara] : 0;
}

const str = 'aaaaaabbbcc';
const counts_a = countCharInStr(str, 'a');
console.log(counts_a); // 6

forループで文字列をループさせるC言語チックな書き方も出来るがlet a of b構文を使うと簡潔に書ける。オブジェクトのキーチェックはkey in obj構文で行っている。文字列のループ部分はES6環境ならspread演算子1を使って以下のようにも書ける2

function countCharInStr(str, chara) {
  const counts = {};
  [...str].map((c) => {
    counts[c] = c in counts ? counts[c] + 1 : 1;
  });
  return chara in counts ? counts[chara] : 0;
}

ちなみに各文字の全体の出現頻度(度数)が必要な場合はcountsオブジェクトをそのままreturnしてよしなにすればよい。


  1. …(ドット3つ)というやつ。スプレッド演算子 - JavaScript | MDN

  2. こっちの方が簡潔かも。まぁ好みの問題ではある。