简体   繁体   中英

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

I think I'm not doing it right at all... Am I going in the right direction? I tried to implement loops to check if each letter in the string "beg" matched the letters in the array.

"beg" is a text that is already provided for my assignment

 // // ***(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="ans15" // 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 is missing, at alphabet , a comma is missing and some other mistakes are inside commented.

At least it is then working code with some small changes.

 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="ans15"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM