可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to count the number of occurrences of each character in a given string using JavaScript.
For example:
var str = "I want to count the number of occurances of each char in this string";
Output should be:
h = 4; e = 4; // and so on
I tried searching Google, but didn't find any answer. I want to achieve something like this; order doesn't matter.
回答1:
This is really, really simple in JavaScript (or any other language that supports maps):
// The string var str = "I want to count the number of occurances of each char in this string"; // A map (in JavaScript, an object) for the character=>count mappings var counts = {}; // Misc vars var ch, index, len, count; // Loop through the string... for (index = 0, len = str.length; index
Now counts
has properties for each character; the value of each property is the count. You can output those like this:
for (ch in counts) { console.log(ch + " count: " + counts[ch]); }
回答2:
function cauta() { var str = document.form.stringul.value; str = str.toLowerCase(); var tablou = []; k = 0; //cautarea caracterelor unice for (var i = 0, n = 0; i -1) { ++count; pos = str.indexOf(char, ++pos); } document.getElementById("rezultat").innerHTML += tablou[i] + ":" + count + '\n'; count = 0; } } }
This function will put each unique char in array, and after will find the appearances of each char in str. In my Case, i get and put data into
回答3:
This worked well for me :
function Char_Count(str1) { var chars = {}; str1.replace(/\S/g, function(l){chars[l] = (isNaN(chars[l]) ? 1 : chars[l] + 1);}); return chars; } var myString = "This is my String"; console.log(Char_Count(myString));
回答4:
I am giving you very very simple code.
// Converts String To Array var SampleString= Array.from("saleem"); // return Distinct count as a object var allcount = _.countBy(SampleString, function (num) { return num; }); // Iterating over object and printing key and value _.map(allcount, function(cnt,key){ console.log(key +":"+cnt); }); // Printing Object console.log(allcount);
Set the variable to different value and then try...
回答5:
// Converts String To Array var SampleString= Array.from("saleem"); // return Distinct count as a object var allcount = _.countBy(SampleString, function (num) { return num; }); // Iterating over object and printing key and value _.map(allcount, function(cnt,key){ console.log(key +":"+cnt); }); // Printing Object console.log(allcount);
Set the variable to different value and then try...