Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การนับคู่คำที่อยู่ติดกันใน 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