javascript 计算字符串中每个字符的出现次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19480916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:43:34  来源:igfitidea点击:

Count number of occurrences for each char in a string

javascript

提问by JS-coder

I want to count the number of occurrences of each character in a given string using JavaScript.

我想使用 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.

我试着用谷歌搜索,但没有找到任何答案。我想实现这样的目标;顺序无关紧要。

回答by T.J. Crowder

This is really, really simple in JavaScript (or any other language that supports maps):

这在 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;
}

Now countshas properties for each character; the value of each property is the count. You can output those like this:

现在counts每个角色都有属性;每个属性的值是计数。你可以这样输出:

for (ch in counts) {
    console.log(ch + " count: " + counts[ch]);
}

回答by Vitaly Volynsky

Shorter answer, with reduce:

更简短的答案,减少:

let s = 'hello';
var result = [...s].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {}); 
console.log(result); // {h: 1, e: 1, l: 2, o: 1}

回答by Atul Kumar Srivastava

let str = "atul kumar srivastava";
let obj ={};
for(let s of str)if(!obj[s])obj[s] = 1;else obj[s] = obj[s]  + 1;
console.log(obj)

回答by seanculleng

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));

回答by Salim Ansari

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);
<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>
    

回答by Salim Ansari

 // 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>
    

回答by Parthasarathy K

Hope this helps someone

希望这有助于某人

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;
}

回答by abdul rehman kk

    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();  // using hashMap<key , value > here key = character and  value = count

    String arr = "HelloWorld";

    for (int i = 0; i < arr.length(); i++) {
        boolean flag = sHashMap.containsKey(arr.charAt(i));  // check if char is already  present 

    if (flag == true)
        {
            int Count = sHashMap.get(arr.charAt(i)); // get the char count
            sHashMap.put(arr.charAt(i), ++Count); //   increment the count and update in hashMap
        } 
        else 
        {
            sHashMap.put(arr.charAt(i), 1); //if  char not present then insert into hashMap
        }
    }

     System.out.println(sHashMap);
    //OutPut would be like ths {r=1, d=1, e=1, W=1, H=1, l=3, o=2}

}

}

回答by Vishwanath

I have used Map object , The map object doesn't let you set any duplicate key and that makes our job easy . I am checking if the key already exists in map , if not I am inserting and setting the count to 1 , if it already exists I am getting the value and then incrementing

我使用了 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)
    })

回答by Dumitru Boaghi

    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;
        }
        }

    }

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

该函数将每个唯一的字符放入数组,然后查找每个字符在 str 中的出现。在我的情况下,我获取并将数据放入