1.11M Members

Character Count in String

 
0
 

Problem :
String : Hello World

Output :

H occured 1 times
e occured 1 times
l occured 3 times
o occured 2 times
W occured 1 times
r occured 1 times
d occured 1 times

How to do it in Javascript...

 
0
 

There's probally a simpler way, but this should work:

var myString = "Hello Word";
var counters = {};

// Count letters
for(var i=0, l=myString.length,c; i<l, c=myString[i]; i=i+1) {
    if ( typeof counters[c] != 'undefined' ) {
        counters[c] = 1;
    }
    else {
        counters[c] = counters[c] + 1;
    }
}

// Show letters
for(var c in counters) {
    document.write(c + ' ocurred ' + counters[c] + ' times');
}
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: