1

I want to search an array to see if it contains a specific string, and then get the index of the result.

For example, if I had:

array[0] = "dogs";
array[1] = "cats";
array[2] = "oranges";

I want to be able to search for "oran" and get 2 back. Any idea on how to do this?

2 Answers 2

4

You can do something like this:

function findInArray(str:String):int {
    for(var i:int = 0; i < array.length; i++){
        if(array[i] == str){
            trace("found it at index: " + i);
            return i;
        }
    }
    return -1; //If not found
}

Then whenever you want to find something call it like:

findInArray("oranges"); // Returns 2

To search for a part of the word can pontentially return undesiderd results for bigger lists, but you can do it with the following:

function findInArrayPartially(str:String):int {
    for(var i:int = 0; i < array.length; i++){
        if(array[i].indexOf(str) > -1){
            trace("found it at index: " + i);
            return i;
        }
    }
    return -1; //If not found
}
Sign up to request clarification or add additional context in comments.

2 Comments

I saw this, but I want to find a string inside a string. Like if I gave it just "orang" it would still give back 2 because "orang" is part of "oranges"
see my edit, I just changed a line to essentially search for the string
1

Another way to do it:

var arr:Array = ["dogs", "cats", "oranges", "apples"];

function indexOfSubstring(array:Array, stringToFind:String):int
{
    var answer:int = array.indexOf(stringToFind);

    if (answer == -1)
    {
        var separator:String = "|";
        var arrayToString:String = array.join(separator);
        var indexInString:int = arrayToString.indexOf(stringToFind);

        if (indexInString != -1)
        {
            var shorterStr:String = arrayToString.substring(0, indexInString);
            answer = shorterStr.split(separator).length - 1;
        }
    }

    return answer;
}

trace(indexOfSubstring(arr, "oran")); // returns 2
trace(indexOfSubstring(arr, "les")); // returns 3
trace(indexOfSubstring(arr, "ts")); // returns 1
trace(indexOfSubstring(arr, "broom")); // returns -1

1 Comment

while this can work in cases where you know what may be in the strings, it can give invalid results if the strings in your array had the separator character in them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.