Count number of occurrences for each char in a string

后端 未结 11 2328
挽巷
挽巷 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 18:15

        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

提交回复
热议问题