gpt4 book ai didi

javascript - 计算重复字符

转载 作者:行者123 更新时间:2023-12-02 17:17:45 26 4
gpt4 key购买 nike

我想按输入顺序计算重复字符。这是我的代码。

<textarea id="field"></textarea>
<input type="submit" name="sub" id="sub" value="GO" />
<div id="charNum"></div>

$("#sub").click(function () {
var all = "abcdefghijklmnopqrstuvwxyz";
var str = $("#field").val();
var text = "";
for (var i = 0; i < all.length; i++) {
var char = all.charAt(i);
if (str.split(char).length > 1) text += str.split(char).length - 1 + "<br>";
}
$("#charNum").html(text);
});

如果我输入'mmani',我会得到输出'1121',它按字母顺序检查。我想要这样的输出:'2111'

最佳答案

请查看代码中的注释以进行解释。

var k = "mamma mia miami".split('')

//if you want to exclude spaces
//var k = "mamma mia miami".split(/\s+/).join('').split('')

var p = {};
//count frequency of every character
for(var i=0;i<k.length;i++) {
var currentChar = k[i];
if(p[currentChar] == undefined) {
//initialize counter for new char found
p[currentChar]=1;
} else {
//increment counter for every next match for that char
p[currentChar]++;
}
}

var output = '';
//format output according to your need
for(each in p) {
output += p[each]
}

关于javascript - 计算重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24259153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com