ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริง str ที่แสดง asentence เป็นอาร์กิวเมนต์เดียว
ฟังก์ชันของเราควรนับและส่งคืนคู่ของคำที่เหมือนกันที่อยู่ติดกันใน stringstr หน้าที่ของเราควรตรวจสอบคำโดยไม่สนใจตัวพิมพ์ ซึ่งหมายความว่า "มัน" และ "มัน" ควรถือว่าเหมือนกัน
ตัวอย่างเช่น หากอินพุตของฟังก์ชันคือ −
ป้อนข้อมูล
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