最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Each Character occurrence in a string - Stack Overflow

programmeradmin0浏览0评论

How to write a javascript code that counts each character occurrence in a string ?

e.g 
String is : Hello World 

Output :  
count of H -> 1
count of e -> 1
count of l -> 3
count of o -> 2 
count of r -> 1
count of d -> 1 
count of W -> 1 

How to write a javascript code that counts each character occurrence in a string ?

e.g 
String is : Hello World 

Output :  
count of H -> 1
count of e -> 1
count of l -> 3
count of o -> 2 
count of r -> 1
count of d -> 1 
count of W -> 1 
Share Improve this question edited Feb 10, 2013 at 13:11 Rachel Gallen 28.6k22 gold badges75 silver badges86 bronze badges asked Feb 10, 2013 at 13:08 VikashVikash 4591 gold badge4 silver badges11 bronze badges 1
  • i tried split, match but it didnt work ... – Vikash Commented Feb 10, 2013 at 13:11
Add a ment  | 

4 Answers 4

Reset to default 11
var counts = {};
yourstring.split('').map(function(ch) {
  counts[ch] = (counts[ch] || 0) + 1;
});

Or be hip and use map/reduce:

var counts = yourstring.split('').reduce(function(dst, c) {
  dst[c] = (dst[c] || 0) + 1;
  return dst;
}, {});

this code should work:

var str = "Hello World";
var arr = str.split('');
var occ = {};
for(var i=0,c=arr.length;i<c;i++){
    if(occ[arr[i]]) occ[arr[i]]++;
    else occ[arr[i]] = 1;
}
for(var i in occ){
    alert('count of '+i+' -> '+occ[i]); 
}
var splitWord = "Hello World".split('');
var letters = {};
for(var i in splitWord)
{
    var letter = splitWord[i];
    if(letter == ' ') continue;
    if(typeof letters[letter] == 'undefined')
    {
        letters[letter] = 0;
    }
    letters[letter]++;
}
console.dir(letters);

Below is my solution with the old and simple for loop. This approach answers the question in the simplest possible way for beginners. This code will convert all the letters in the input to lower case and count their occurrence. In this solution, we also count the special characters and spaces as valid characters.

  function countChar(str) {
            var count = {};
            for (let i = 0; i < str.length; i++) {
                var ch = str[i].toLowerCase();
                if (count[ch] > 0) {
                    count[ch]++;
                } else {
                    count[ch] = 1;
                }
            }
            return count;
        }

The count object denotes the characters in the input.

发布评论

评论列表(0)

  1. 暂无评论