PDA

View Full Version : array index for given string value


klebedaja
09-29-2010, 05:57 PM
Hi people,
I'm interested if there is a procedure that returns me index of array for given string.
Better with example:

string $array[] = ("a", "b", "c", "d");
string $letter = "c";

I need a procedure that will return me array index for "c", which is 2.
a 0
b 1
c 2
d 3
Couldnt find any help.
Thanks.

Byterunner
09-29-2010, 06:08 PM
Nothing built into Maya that I'm aware of, but it's easy enough to write.

proc int stringArrayIndex(string $array[], string $index)
{
for($i=0;$i<size($array);$i++)
{
if($array[$i] == $index)
return $i;
}
return -1;
}

print(stringArrayIndex({"a", "b", "c", "d"}, "c"));

// Result: 2

Edit: I forgot to mention, this will not work well if you happen to have more than one item in your array with the same name as what you're searching for. It will only return the first instance of it. You can expand it to return a list of indices fairly easily, though, if you need that sort of functionality. Also, there's probably a far easier way to do this in Python, I just haven't gotten that far into the migration from MEL yet.

Morganism
09-29-2010, 08:01 PM
Yeah, in python it's super easy:

['a','b','c','d'].index('c')

nessus
09-30-2010, 01:45 AM
Here you go, updated to return all the indices found in given array if you still use MEL:

global proc int[] stringArrayIndex(string $array[], string $index)
{
int $indices[];
for($i=0;$i<size($array);$i++)
{
if($array[$i] == $index)
$indices[size($indices)]=$index;
}
return $indices;
}

print(stringArrayIndex({"a", "b", "c", "d"}, "c"));

klebedaja
09-30-2010, 09:10 AM
Thanks guys very much.
I thought meaby there is some proc like in phyton is.
Anyway Byterunner's & nessus's proc will help a lot and Morganism thanks for the phyton hint.
Thanks, buy.

CGTalk Moderation
09-30-2010, 09:10 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.