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

เปรียบเทียบคะแนน ASCII ของสตริง - JavaScript

คำนวณผลรวมรหัส ASCII (charCodeAt) ของทุกตัวอักษรในสตริงสองสตริง แล้วหาความต่างสัมบูรณ์

ตัวอย่างโค้ด

const str1 = 'This is the first string.';
const str2 = 'This here is the second string.';

const calculateScore = (str = '') => {
  return str.split('').reduce((acc, val) => {
    return acc + val.charCodeAt(0);
  }, 0);
};

const compareASCII = (str1, str2) => {
  const firstScore = calculateScore(str1);
  const secondScore = calculateScore(str2);
  return Math.abs(firstScore - secondScore);
};

console.log(compareASCII(str1, str2));

ผลลัพธ์

536

การประยุกต์ใช้

  • ตรวจสอบความคล้ายคลึงของสตริง (string similarity)
  • Simple checksum สำหรับข้อมูลสั้น
  • การจัดเรียงสตริงแบบ custom

หมายเหตุ: charCodeAt(0) ให้ค่า UTF-16 code unit ซึ่งสำหรับ ASCII (0-127) จะตรงกับค่า ASCII มาตรฐาน