Count number of occurrences for each char in a string

后端 未结 11 2225
挽巷
挽巷 2020-12-16 17:42

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         


        
相关标签:
11条回答
  • 2020-12-16 17:58

    You can use the maps in ES6 in Javascript. Provides a cleaner and concise code in my opinion. Here is how I would go about

    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]
    }  
    
    
    0 讨论(0)
  • 2020-12-16 18:00

    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;
    }
    
    0 讨论(0)
  • 2020-12-16 18:02

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

    0 讨论(0)
  • 2020-12-16 18:07

    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));
    
    0 讨论(0)
  • 2020-12-16 18:07

    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>
        

    0 讨论(0)
  • 2020-12-16 18:08
        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}
    
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题