使用 JavaScript 統計並返回出現在 str2 中的 str1 字數


問題

我們需要編寫一個 JavaScript 函式,它把兩個字串作為第一個和第二個引數接收,分別是 str1 和 str2。

我們的函式應該統計並返回出現在 str2 中的 str1 字元數,如果有重複出現,我們必須單獨統計。

例如,如果輸入函式的是

輸入

const str1 = 'Kk';
const str2 = 'klKKkKsl';

輸出

const output = 5;

樣例

以下是程式碼 −

 執行演示

const str1 = 'Kk';
const str2 = 'klKKkKsl';
var countAppearances = (str1 = '', str2 = '') => {
   const map = {}
   for(let c of str1) {
      map[c] = true
   }
   let count = 0
   for(let c of str2) {
      if(map[c]) {
         count+=1
      }
   }
   return count
};
console.log(countAppearances(str1, str2));

輸出

5

更新於: 24-4-2021

127 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.