在 JavaScript 中計算相鄰成對的單詞


問題

我們需要編寫一個 JavaScript 函式,它接受一個字串 str,表示一個句子作為唯一引數。

我們的函式應計算並返回字串 str 中存在的成對的相同單詞。我們的函式應檢查單詞而不考慮其大小寫,這意味著“it”和“It”應計為相同。

例如,如果輸入函式的是 -

輸入

const str = 'This this is a a sample string';

輸出

const output = 2;

輸出說明

因為重複的單詞是“this”和“a”。

示例

以下是程式碼 -

 即時演示

const str = 'This this is a a sample string';
const countIdentical = (str = '') => {
   const arr = str.split(' ');
   let count = 0;
   for(let i = 0; i < arr.length - 1; i++){
      const curr = arr[i];
      const next = arr[i + 1];
      if(curr.toLowerCase() === next.toLowerCase()){
         count++;
      };
   };
   return count;
};
console.log(countIdentical(str));

輸出

2

更新於: 2021-04-22

245 次瀏覽

開啟您的事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.