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

การรวมสตริงสองตัวสลับกันทีละสองตัวอักษร (Twice Join) ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีรวมสตริงสองตัว โดยสลับกันทีละ 2 ตัวอักษรจากแต่ละสตริง

ตัวอย่าง

str1 = 'Hello world'
str2 = 'How are you btw'

Output: 'HeHollw o arwoe rlyodu btw'
// He + Ho + ll + ow + ... (สับสนมาก)

Logic: เข้าสลับกันทีละ 2 chars จาก str1, str1, str2, str2, str1, str1, ...

การนำไปใช้

const twiceJoin = (str1 = '', str2 = '') => {
  let res = '', i = 0, j = 0;
  
  for (let ind = 0; i < str1.length; ind++) {
    if (ind % 2 === 0) {
      // จาก str1
      res += (str1[i] || '') + (str1[i + 1] || '');
      i += 2;
    } else {
      // จาก str2
      res += (str2[j] || '') + (str2[j + 1] || '');
      j += 2;
    }
  }
  
  // เหลือ str2
  while (j < str2.length) {
    res += str2[j++];
  }
  
  return res;
};

console.log(twiceJoin('Hello world', 'How are you btw'));

ผลลัพธ์

HeHollw o arwoe rlyodu btw

วิธีที่เข้าใจง่ายกว่า (Chunk by 2)

const chunk = (str, size) => 
  Array.from({ length: Math.ceil(str.length / size) }, (_, i) => 
    str.slice(i * size, (i + 1) * size)
  );

const twiceJoinClear = (str1, str2) => {
  const chunks1 = chunk(str1, 2);
  const chunks2 = chunk(str2, 2);
  const maxLen = Math.max(chunks1.length, chunks2.length);
  
  let res = '';
  for (let i = 0; i < maxLen; i++) {
    if (chunks1[i]) res += chunks1[i];
    if (chunks2[i]) res += chunks2[i];
  }
  return res;
};

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

  • String Interleaving / Shuffling
  • Data Obfuscation
  • Stream Multiplexing (Simple)
  • Cryptography: Simple Transposition Cipher

ข้อควรระวัง

  • Logic ของโค้ดต้นฉบับซับซ้อนและอาจมี Bug (Loop Condition: `i < str1.length` แต่ `ind` เพิ่มทุกรอบ)
  • Unicode: ใช้ `[...str]` แทน index access
  • การจัดการ Leftover Characters