我想使用JavaScript计算给定字符串中每个字符的出现次数。
例如:
var str = "I want to count the number of occurances of each char in this string";
输出应为:
h = 4;
e = 4; // and so on
我尝试搜索Google,但未找到任何答案。我希望实现this之类的东西;顺序无所谓。
答案 0 :(得分:12)
这在JavaScript(或支持地图的任何其他语言)中非常简单:
// 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 < len; ++index) {
// Get this character
ch = str.charAt(index); // Not all engines support [] on strings
// Get the count for it, if we have one; we'll get `undefined` if we
// don't know this character yet
count = counts[ch];
// If we have one, store that count plus one; if not, store one
// We can rely on `count` being falsey if we haven't seen it before,
// because we never store falsey numbers in the `counts` object.
counts[ch] = count ? count + 1 : 1;
}
现在counts
具有每个角色的属性;每个属性的值是计数。您可以输出以下内容:
for (ch in counts) {
console.log(ch + " count: " + counts[ch]);
}
答案 1 :(得分:2)
您可以将对象用于任务。
第一步 - 创建一个对象
第 2 步 - 遍历字符串
步骤 3 - 在对象中添加字符作为键和字符计数作为值
var obj={}
function countWord(arr)
{
for(let i=0;i<arr.length;i++)
{
if(obj[arr[i]]) //check if character is present in the obj as key
{
obj[arr[i]]=obj[arr[i]]+1; //if yes then update its value
}
else
{
obj[arr[i]]=1; //initialise it with a value 1
}
}
}
答案 2 :(得分:2)
我遍历每个字符并将其与计数一起放入嵌套对象中。如果该字符已存在于对象中,我只需增加计数。 这是 myObj 的样子:
myObj = {
char1 = { count : <some num> },
char2 = { count : <some num> },
....
}
代码如下:
function countChar(str) {
let myObj= {};
for (let s of str) {
if ( myObj[s] ? myObj[s].count ++ : myObj[s] = { count : 1 } );
}
return myObj;
}
var charCount = countChar('abcceddd');
答案 3 :(得分:2)
//this will update all iCheck fields inside the selected form
$('#form_id :radio').iCheck('update');
答案 4 :(得分:1)
这对我很有用:
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));
答案 5 :(得分:1)
单行 ES6 方式:
const some_string = 'abbcccdddd';
const charCountIndex = [ ...some_string ].reduce( ( a, c ) => ! a[ c ] ? { ...a, [ c ]: 1 } : { ...a, [ c ]: a[ c ] + 1 }, {} );
console.log( charCountIndex )
答案 6 :(得分:1)
str = "aaabbbccccdefg";
words = str.split("");
var obj = [];
var counter = 1, jump = 0;
for (let i = 0; i < words.length; i++) {
if (words[i] === words[i + 1]) {
counter++;
jump++;
}
else {
if (jump > 0) {
obj[words[i]] = counter;
jump = 0;
counter=1
}
else
obj[words[i]] = 1;
}
}
console.log(obj);
答案 7 :(得分:1)
您可以使用Javascript在ES6中使用地图。我认为提供了更简洁的代码。这就是我要怎么做
function countChrOccurence ('hello') {
let charMap = new Map();
const count = 0;
for (const key of str) {
charMap.set(key,count); // initialize every character with 0. this would make charMap to be 'h'=> 0, 'e' => 0, 'l' => 0,
}
for (const key of str) {
let count = charMap.get(key);
charMap.set(key, count + 1);
}
// 'h' => 1, 'e' => 1, 'l' => 2, 'o' => 1
for (const [key,value] of charMap) {
console.log(key,value);
}
// ['h',1],['e',1],['l',2],['o',1]
}
答案 8 :(得分:0)
使用扩展 ...
运算符而不是 .split('')
拆分字符串:
'????'.split('')
//=> ["\ud83c", "\udf2f", "\ud83c", "\udf2f", "\ud83c", "\udf63", "\ud83c", "\udf7b"]
对比
[...'????']
//=> ["?", "?", "?", "?"]
对比
'?'.charAt(0)
//=> "\ud83c"
然后减少:
[...'????'].reduce((m, c) => (m[c] = (m[c] || 0) + 1, m), {})
//=> {'?': 2, '?': 1, '?': 1}
答案 9 :(得分:0)
我尝试了检查“空白空间”和“特殊字符”:
function charCount(str){
const requiredString = str.toLowerCase();
const leng = str.length;
let output = {};
for(let i=0; i<leng; i++){
const activeCharacter = requiredString[i];
if(/[a-z0-9]/.test(activeCharacter)){
output.hasOwnProperty(activeCharacter) ? output[activeCharacter]++ : output[activeCharacter] = 1;
}
}
return output;
}
答案 10 :(得分:0)
let newStr= "asafasdhfasjkhfweoiuriujasfaksldjhalsjkhfjlkqaofadsfasasdfas";
function checkStringOccurnace(newStr){
let finalStr = {};
let checkArr = [];
let counterArr = [];
for(let i = 0; i < newStr.length; i++){
if(checkArr.indexOf(newStr[i]) == -1){
checkArr.push(newStr[i])
let counter = 0;
counterArr.push(counter + 1)
finalStr[newStr[i]] = 1;
}else if(checkArr.indexOf(newStr[i]) > -1){
let index = checkArr.indexOf(newStr[i])
counterArr[index] = counterArr[index] + 1;
finalStr[checkArr[index]] = counterArr[index];
}
}
return finalStr;
}
let demo = checkStringOccurnace(newStr);
console.log(" finalStr >> ", demo);
答案 11 :(得分:0)
我使用了Map对象,该map对象不允许您设置任何重复的键,这使我们的工作变得容易。我正在检查该键是否已经存在于map中,如果不存在,我将插入计数并将其设置为1,如果它已经存在,则获取值,然后递增
const str = "Hello H"
const strTrim = str.replace(/\s/g,'') // HelloH
const strArr=strTrim.split('')
let myMap = new Map(); // Map object
strArr.map(ele=>{
let count =0
if(!myMap.get(ele)){
myMap.set(ele,++count)
}else {
let cnt=myMap.get(ele)
myMap.set(ele,++cnt)
}
console.log("map",myMap)
})
答案 12 :(得分:0)
更短的答案,并减少:
let s = 'hello';
[...s].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {});
// {h: 1, e: 1, l: 2, o: 1}
答案 13 :(得分:0)
package com.company;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// write your code here
HashMap<Character, Integer> sHashMap = new HashMap();
String arr = "HelloWorld";
for (int i = 0; i < arr.length(); i++) {
boolean flag = sHashMap.containsKey(arr.charAt(i)); // check if char is present
if (flag == true) {
int Count = sHashMap.get(arr.charAt(i)); // get the value count
sHashMap.put(arr.charAt(i), ++Count); // increment the count and update value
} else {
sHashMap.put(arr.charAt(i), 1); // character not present then insert into hash
}
}
System.out.println(sHashMap);
//OutPut would be like ths {r=1, d=1, e=1, W=1, H=1, l=3, o=2}
}
}
答案 14 :(得分:0)
希望这对某人有帮助
function getNoOfOccurences(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
if(typeof temp[str.charAt(oindex)] == 'undefined'){
temp[str.charAt(oindex)] = 1;
}else{
temp[str.charAt(oindex)] = temp[str.charAt(oindex)]+1;
}
}
return temp;
}
答案 15 :(得分:0)
// 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);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<p>Set the variable to different value and then try...</p>
&#13;
答案 16 :(得分:0)
我给你非常简单的代码。
// 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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<p>Set the variable to different value and then try...</p>
答案 17 :(得分:0)
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 < str.length; i++) {
for (var j = 0; j < tablou.length; j++) {
if (tablou[j] == str[i]) k = 1;
}
if (k != 1) {
if (str[i] != ' ')
tablou[n] = str[i]; n++;
}
k = 0;
}
//numararea aparitilor
count = 0;
for (var i = 0; i < tablou.length; i++) {
if(tablou[i]!=null){
char = tablou[i];
pos = str.indexOf(char);
while (pos > -1) {
++count;
pos = str.indexOf(char, ++pos);
}
document.getElementById("rezultat").innerHTML += tablou[i] + ":" + count + '\n';
count = 0;
}
}
}
这个函数会将每个唯一的char放在数组中,然后放在数组中 找到str中每个char的外观。在我的案例中,我得到并放置数据 进入