views:

1839

answers:

4

How do I accomplish this in actionscript (example in c#):

string[] arr = { "1.a", "2.b", "3.d", "4.d", "5.d" };
int countD = 0;

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i].Contains("d")) countD++;
}

I need to count a character in an array of strings

A: 

Use the match function on a javascript string. http://www.cev.washington.edu/lc/CLWEBCLB/jst/js_string.html

Sorry, works the same.

Daniel A. White
I need to do this in actionscript2 (flash8)
callisto
"Sorry, works the same." Please explain.
callisto
JavaScript and ActionScript are both EcmaScript and the string object works the same on both.
Daniel A. White
+2  A: 

Try this:

for(var i:int = 0; i < arr.Length; i++)
{
    if(arr[i].indexOf("d") != -1)
        countD++;
}

Use indexOf rather than contains. It will return -1 if the character is not in the string, otherwise the string contains at least one instance.

Justin Niessner
thanks for the point, although I actually need to do this in actionscript2 (flash8)
callisto
According to Adobe, indexOf was supported as far back as Flash 5: http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary692.html
Justin Niessner
you need to mention the actionscript 2 requirement in your question
Ryan Guill
A: 

Found it:

var searchString:String = "Lorem ipsum dolor sit amet.";
var index:Number;

index = searchString.indexOf("L");
trace(index); // output: 0

index = searchString.indexOf("l");
trace(index); // output: 14

index = searchString.indexOf("i");
trace(index); // output: 6

index = searchString.indexOf("ipsum");
trace(index); // output: 6

index = searchString.indexOf("i", 7);
trace(index); // output: 19

index = searchString.indexOf("z");
trace(index); // output: -1
callisto
A: 

Here are four ways to do it... (well, 3.something)

var myString:String = "The quick brown fox jumped over the lazy "
           + "dog. The quick brown fox jumped over the lazy dog.";
var numOfD:int = 0;

// 1# with an array.filter
numOfD = myString.split("").filter(
   function(s:String, i:int, a:Array):Boolean {
    return s.toLowerCase() == "d"
         }
        ).length;

trace("1# counts ", numOfD); // output 1# counts 4


// 2# with regex match
numOfD = myString.match(/d/gmi).length;
trace("2# counts ", numOfD); // output 2# counts 4

// 3# with for loop
numOfD = 0;
for (var i:int = 0; i < myString.length; )
 numOfD += (myString.charAt(++i).toLocaleLowerCase() == "d");
trace("3# counts ", numOfD); // output 3# counts 4

// 4# with a new prototype function (and regex)
String['prototype'].countOf = 
 function(char:String):int { 
  return this.match(new RegExp(char, "gmi")).length;
 };
// -- compiler 'strict mode' = true
numOfD = myString['countOf']("d");
trace("4# counts ", numOfD); // output 4# counts 4
// -- compiler 'strict mode' = false
numOfD = myString.countOf("d");
trace("4# counts ", numOfD); // output 4# counts 4
Ben
stackoverflow code parser is fail
Ben