Welcome to my actionscript snippet library!

Actionscript Snips is a small repository of actionscript code that aims to save developers and designers time when developing a website.  

Count All Occurrences of a Character In a String


var str:String = "programmer";
var char:String = "m";

function countOccurences(str:String, char:String):Number {
var count:Number = 0;

for(var i=0; i < str.length; i++) {
if (str.charAt(i) == char) {
count++;
}
}
return count;
}

trace(countOccurences(str, char)); //Outputs 2

2 comments:

zappan said...

trace(str.split(char).length-1);
Would do the trick ;)

Unknown said...

function count(pattern:String, target:String) : uint {
var count:uint=0;
var index:int = -1;
while((index = target.indexOf(pattern, index+1)) >= 0){
count++;
}
return count;
}

Post a Comment