"إذا أراد العامل أن يؤدي عمله بشكل جيد، فعليه أولاً أن يشحذ أدواته." - كونفوشيوس، "مختارات كونفوشيوس. لو لينجونج"
الصفحة الأمامية > برمجة > كرر الحرف في سلسلة بناءً على فهرسه الأبجدي

كرر الحرف في سلسلة بناءً على فهرسه الأبجدي

تم النشر بتاريخ 2024-11-03
تصفح:178

Repeat the Character in a string based on its Alphabetical index

اكتب دالة RepeatAlpha تأخذ سلسلة وتعرضها
تكرار كل حرف أبجدي عدة مرات مثل الفهرس الأبجدي الخاص به.

حل

const range = (start, stop, step) =>
  Array.from(
    { length: Math.ceil((stop - start) / step) },
    (_, i) => start   i * step
  );

const upperAlpha = range("A".charCodeAt(0), "Z".charCodeAt(0)   1, 1).map((x) =>
  String.fromCharCode(x)
);

const lowerAlpha = range("a".charCodeAt(0), "z".charCodeAt(0)   1, 1).map((x) =>
  String.fromCharCode(x)
);

function getAlphaIndex(char) {
  if (char === char.toUpperCase()) {
    return upperAlpha.indexOf(char)   1;
  }

  if (char === char.toLowerCase()) {
    return lowerAlpha.indexOf(char)   1;
  }
}

function repeatAlpha(text) {
  let occurrence = [];

  Array.from(text).forEach((char) => {
    let count = getAlphaIndex(char);
    let result = Array(count).fill(char).join("");
    occurrence.push(result);
  });

  return occurrence.join("");
}

console.log(repeatAlpha("Becky"));
console.log(repeatAlpha("neNgi"));
console.log(repeatAlpha("ChInwendu"));
console.log(repeatAlpha("dindustack"));

نتيجة

BBeeeeeccckkkkkkkkkkkyyyyyyyyyyyyyyyyyyyyyyyyy
nnnnnnnnnnnnnneeeeeNNNNNNNNNNNNNNgggggggiiiiiiiii
CCChhhhhhhhIIIIIIIIInnnnnnnnnnnnnnwwwwwwwwwwwwwwwwwwwwwwweeeeennnnnnnnnnnnnndddduuuuuuuuuuuuuuuuuuuuu
ddddiiiiiiiiinnnnnnnnnnnnnndddduuuuuuuuuuuuuuuuuuuuusssssssssssssssssssttttttttttttttttttttaccckkkkkkkkkkk
بيان الافراج تم إعادة إنتاج هذه المقالة على: https://dev.to/dindustack/repeat-the-character-in-a-string-based-on-its-alphabetical-index-1ln7?1 إذا كان هناك أي انتهاك، يرجى الاتصال بـ Study_golang @163.com حذف
أحدث البرنامج التعليمي أكثر>

تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.

Copyright© 2022 湘ICP备2022001581号-3