存储字母表中每个字母在所需位置的字符串中出现的次数

Storing number of times each letter of the alphabet appears in a string in a desired location

本文关键字:字符串 位置 字母表 存储      更新时间:2023-09-26

我觉得我做得一点也不对...我走对了方向吗?我尝试实现循环来检查字符串"beg"中的每个字母是否与数组中的字母匹配。

"乞求"是已经为我的作业提供的文本

//
// ***(15)  store the number of times the letter "a" appears in the string "beg" in 1st location;
// ***      store the number of times the letter "b" appears in the string "beg" in 2nd location;
// ***      store the number of times the letter "c" appears in the string "beg" in 3rd location;
// ***      store the number of times the letter "d" appears in the string "beg" in 4th location;
// ***      etc.
// ***      show the 26 counts on one line separated by commas in the span block with id="answers15"
//
var alphaNum = [26];
var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"
  "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
];
for (i = 0; i < 26; i++) {
  alphaNum[i] = 0;
}
for (i = 0; i < beg.length; j++) {
  charNow = beg.substr(i, 1);
  for (j = 0; j < 26; j++) {
    if (charNow == alphabet[j])
      alphaNum = alphaNum[j] + 1;
  }
}
showAlpha = "";
for (i = 0; i < 26; i++) {
  showAlpha = showAlpha + alphabet[i] + ": " + alphaNum[i] + "<br>"
}
ans15.innerHTML = showAlpha;

缺少

beg,在alphabet,缺少逗号,并在注释中注释了其他一些错误。

至少它是带有一些小更改的工作代码。

var beg = 'store the number of times the letter "a" appears in the string "beg" in 1st location;', // declaration missing
    alphaNum = [],          // empty array, not an array with one element 26
    alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
    i, j,           // declaration missing
    charNow,        // declaration missing
    showAlpha = ""; // declaration missing
for (i = 0; i < 26; i++) {
    alphaNum[i] = 0;
}
for (i = 0; i < beg.length; i++) {         // should be i++
    charNow = beg.substr(i, 1);            // could be replaced by charNow = beg[i]
    for (j = 0; j < 26; j++) {
        if (charNow == alphabet[j]) {      // adding some curly brackets
            alphaNum[j] = alphaNum[j] + 1; // index missing
        }
    }
}
for (i = 0; i < 26; i++) {
    showAlpha = showAlpha + alphabet[i] + ": " + alphaNum[i] + "<br>"
}
document.getElementById('ans15').innerHTML = showAlpha; // target missing
<div id="answers15"></div>