在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP