ฟังก์ชันนี้เปรียบเทียบสองสตริงที่มีความยาวเท่ากัน และนับจำนวนตำแหน่งที่ตัวอักษรต่างกัน (corresponding dissimilarities)
ตัวอย่าง
str1: 'Hello world!!!' str2: 'Hellp world111' // ตำแหน่งที่ต่างกัน: index 4 (o/p), 11 (!/1), 12 (!/1), 13 (!/1) = 4 ตำแหน่ง
ตัวอย่างโค้ด
const str1 = 'Hello world!!!';
const str2 = 'Hellp world111';
const dissimilarity = (str1 = '', str2 = '') => {
let count = 0;
for (let i = 0; i < str1.length; i++) {
if (str1[i] === str2[i]) {
continue;
}
count++;
}
return count;
};
console.log(dissimilarity(str1, str2));
ข้อควรระวัง
- โค้ดสมมติว่าสตริงทั้งสองมีความยาวเท่ากัน
- หากความยาวต่างกัน ควรเพิ่มการตรวจสอบหรือจัดการกรณีขอบเขต
ผลลัพธ์
4
ประยุกต์ใช้: การตรวจสอบข้อผิดพลาดการพิมพ์ การเปรียบเทียบ DNA sequence การตรวจสอบ checksum