1,105,375 Community Members

Character Count in String

Member Avatar
livlikestar.jame
Newbie Poster
1 post since Feb 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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...

Member Avatar
AleMonteiro
Master Poster
758 posts since Aug 2010
Reputation Points: 115 [?]
Q&As Helped to Solve: 143 [?]
Skill Endorsements: 29 [?]
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: