在 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