」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 根據字母順序索引重複字串中的字符

根據字母順序索引重複字串中的字符

發佈於2024-11-03
瀏覽:651

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如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3