Count how many times a character appears in a string.
var greeting = "Hello world!";
var hash = {};
for(var i = 0; i < greeting.length; i++)
{
if(hash[greeting[i]] === undefined)
{
hash[greeting[i]] = 1;
} else {
hash[greeting[i]] += 1;
}
}
// printing the stuff in hash.
for(var x in hash)
{
if(hash.hasOwnProperty(x))
{
console.log(x, hash[x]);
}
}
Output:
H 1
e 1
l 3
o 2
1
w 1
r 1
d 1
! 1
We can possibly convert the code into functions.
var generateCharacterHashOfString = function(str)
{
var hash = {};
for(var i = 0; i < greeting.length; i++)
{
if(hash[greeting[i]] === undefined)
{
hash[greeting[i]] = 1;
} else {
hash[greeting[i]] += 1;
}
}
return hash;
};
And the print function:
var printCharacterHash = function(hash)
{
for(var x in hash)
{
if(hash.hasOwnProperty(x))
{
console.log(x, hash[x]);
}
}
};
Then it's just a matter of calling these functions:
var hash = generateCharacterHashOfString("Hello world!");
printCharacterHash(hash);